Setting up multiple file organization in MPLAB without headaches

If you have MPLAB v8 installed (or possibly even with MPLAB X), you are forced to abide by the limitations of the mplink.exe linker. Here is a definitive guide on how to link multiple source files:

1. Use C-style includes. The proper way to do this is to wrap every #include with a #ifndef/#endif pair, and then put the #define directive at the top of the respective file. So, say I have 3 include files called file1.inc, file2.inc, and file3.inc, and file3.inc depends on the first two. So, in my main file, I write:

#ifndef   FILE1

#include <file1.inc>

#endif

#ifndef   FILE2

#include <file2.inc>

#endif

#ifndef  FILE3

#include <file3.inc>

#endif

It is not actually entirely necessary to wrap your includes in your main file, since you are guaranteed that each #include is the first occurrence of that particular #include, but it is good practice to wrap all your includes in all your files.

Since file1 has no dependencies, at the top I write:

#define FILE1

So that the linker will remember that it's been here already. At the top of file3, since it depends on the first two, I write:

#ifndef  FILE1

#include FILE1

#endif

#ifndef  FILE2

#include FILE2

#endif

#define FILE3

2. Most directives should only be used once, at the top of your main file. Including <p16f877.inc> (as an example) means that the linker will only get it once, so there's no need to include it anywhere else. Configuration words can only be set once, so put them there too. Also, the list and errorlevel directives belong there.

3. Indicate your code section. The linker needs to know which sections of your program contain code, which will probably be all of them. The best way to ensure that your code section is "contiguous" is to only have one code section, encompassing all your files. To do this, put the directive _page0_ CODE at the top of your main file, above the includes. Also, put the END directive at the bottom of your main code file only. Do not use these directives anywhere else unless you absolutely need to (you won't unless you run into paging issues). Your main file may look like this:

list p=pic16f877, f=inhx8m, c=160, n=80, st=off, mm=off, r=dec

errorlevel -302


__config(...)

_page0_ code

#include <p16f877.inc>

#include <file1.inc>

#include <file2.inc>

#include <file3.inc>

... your code, macros, constants, cblocks, etc. go here ...

end

Notice that the errorlevel directive is above your includes, unlike in some of the example code. This prevents the linker/compiler from generating stupid warnings in all your files, not just the main file.

Views: 148

Reply to This

© 2024   Created by PML.   Powered by

Badges  |  Report an Issue  |  Terms of Service