The two #define directives have nothing to do with each other, because they are in different translation units (that is, in the source files). The compiler processes the two source files in complete isolation, so defined(VAR) always false, and the contents of #ifndef always included.
If you want to have one variable shared between several source files, there is an easy way: define it in one source file and declare it in another:
// other.cpp int var; // Definition. // main.cpp extern int var; // Declaration.
When linked, they will refer to the same var . Better yet, declare a variable in the header:
Then the files that need var can simply include a header:
// main.cpp
The difference you see between C and C ++ is related to the processing of globally declared identifiers in C compared to C ++. In C, any number of preliminary definitions (without a storage class specifier and without an initializer) can be combined together by the linker into a single character - if all the actual definitions of this character ultimately have the same relationship and storage class. This is done using weak linker characters.
C ++, however, does not have the concept of a test definition and considers an external declaration without a storage class specifier as a definition. Thus, g ++ generates strong linker characters, which leads to conflict during the connection.
source share