g++ -g test.cpp test.h globals.h globals.cpp -o test
/tmp/ccPVNJit.o:(.data+0x0): multiple definition of `GLOB'
/tmp/ccfh0O4a.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
So, no error if GLOB is const or if I do not use global.cpp.
How can I use global variable from another header file that also has source file?
The best solution here is to not use globals. Using globals is bad practice for many reasons, the biggest of which is it makes your code harder to reuse.
A more typical way to share information between functions is to pass the value in question as a parameter.
In your case, I would change your 'foo' function to accept an int parameter. Then you can pass GLOB to it by parameter rather than relying on a global.
Alright, another question, as in the above code, if I have a global variable int GLOB = 100 declared in global.h that I want to use and modify only in global.cpp file, (I also have test.h and test.cpp) but I cannot do it because I have to declare it as const. What to do about it?
As long as the tags are const the project compiles alright. However, I came across a situation when I need to modify few tags inside of message_class. I can move all tags inside of message_class then I would have to declare them and then initialize them in c'tor - that's laborous and error prone considering the large number of tags. Not sure now, make them static?
Just checked, I cannot declare and initialize static string inside of class:
1 2 3 4
staticconst string TAG_BEGIN = "begin"; // does not compile.
staticconstint TAG_INT = 99; // compiles.
Any advice? I am trying to avoid declaring and initializing tags in two places.