Hello,
this code compiles fine but I can't figure out why do I get linker errors:
-------------- Build: Release in test ---------------
Linking console executable: bin\Release\test.exe
obj\Release\header.o:header.cpp:(.bss+0x0): multiple definition of `global_var'
obj\Release\main.o:main.cpp:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
Process terminated with status 1 (0 minutes, 0 seconds)
0 errors, 0 warnings
If I recall, the variable can be declared as many times as you want, but only defined once. The ifndef guards only protect against multiple definitions/declarations in the same translation unit (i.e., cpp file in this case), so when main.cpp and header.cpp are compiled, each defines a global variable 'global_var' and assigns it the value '0'. When the executable is linked, it finds 2 variables with the same name in the same scope, and generates an error.
You can fix the above by changing the header to be externint global_var;
and adding the below to either main.cpp or header.cpp (but not both!) int global_var=0;
It works, but you won't see the changes to global_var in main.cpp, as each translation unit has its own copy of global_var. This may or may not be what you are trying to achieve.