// main.cpp
#include "b.h"
int main(){
b obj;
obj.g();
return 0;
}
I have tried with:
g++ b.cpp main.cpp c.c
but I obtain this errors:
/tmp/ccd2Ed7I.o:(.bss+0x0): multiple definition of `x'
/tmp/cc6G2vTb.o:(.bss+0x0): first defined here
/tmp/ccAjxYki.o:(.bss+0x0): multiple definition of `x'
/tmp/cc6G2vTb.o:(.bss+0x0): first defined here
/tmp/cc6G2vTb.o: In function `b::g()':
b.cpp:(.text+0x21): undefined reference to `h'
collect2: ld returned 1 exit status
You're problem is that you are including the header file in all the cpp files and compiling them all simultaneously. the "ifndef" works for one cpp file and multiple header files calling it, but not between multiple source files. I never understood that my self but I learned to except it :O
You can't define globals this way. A global can only exist in one source file. When you put a global in a header and the #include it in multiple cpp files, each cpp file makes its own global var, and then the linker doesn't know which one to use.
It's the same idea as having a function body in multiple cpp files. You just can't do it.
The solution here:
get rid of the global 'x'. Globals are poor design anyway.