Preprocessor command order

41 Views Asked by At

I know that when I have only one source file in C++, preprocessor commands are done in order they were written, but what if I have more than one source file? How is the decision made, which source file should be taken at first? I've written in both source files such code:

#ifndef b 
#define b 10
int a = 15;
#endif

and when I compile, there is an error, that variable a has been already defined. But why, if there is a command #ifndef and #endif?

1

There are 1 best solutions below

0
On

The order that the compiler processes source files is undefined by the language.

I am assuming you get this error in the linker stage. This is because both your source files define a symbol with the same name, and the linker gives up when trying to merge the object code from each file. If your intent is to let at least one of the files have its own separate version of a, declare it in that file as static. Then the linker error should go away as the static a is limited to its own file.