#define scope in multiple files #define scope in multiple files c c

#define scope in multiple files


Preprocessor is run for each file before it is compiled, i.e. once for main_a.c and then again independently for shared.c. When shared.c is compiled MAIN_A is undefined.

Preprocessor can't be used the way you're attempting, i.e. remembering state across compilation units.

What you can do is define a name (for example MAIN_A) using the -Dcompiler option in your Makefile and test this name using preprocessor the same way you're doing it now. This way the definition takes place on the project level (in the Makefile) rather than on a compilation unit level (in a .c file).


Let me do the preprocessor's work here and expand all your macros. In main.c, MAIN_A is defined, so A is defined. Nothing depends on A in main.c, and i is extern.

In shared.c, MAIN_A and thereby A are undefined, and i is 0.

In short, the preprocessor cannot transport information between compilation units. That's good practice, because otherwise programs would quickly become unreadable and you would have to recompile all compilation units when one unit changes (because symbols might have changed). Resolve the issue by setting i explicitly in main:

 int main() {     i = 1; }

It is more verbose, but is also much clearer to the reader. If you want to encapsulate, define a function InitializeShared. If you truly want to compile some code as a single compilation unit, make one of the files a header file and #include it into the other.


Yes you are right, they are completely separate compilation units.

MAIN_A is only defined in main_a.c

One thought that comes to mind is to cat the files together to make one compilation unit?