I'm having problems with a shared variable by more than one programs invoked from a main piece of code. I can actually make the object code of each file itself, but I'm not able lo link them all because there is a multiple definition problem. My sources are as follows (a simple example to illustrate the code):
If I build the project, the build log shows the following:
obj/Debug/b.o||In function `modifyB()':|
/home/ruben/Proyectos/multiple_inclusion/multiple/b.cc|6|multiple definition of `var'|
obj/Debug/a.o:/home/ruben/Proyectos/multiple_inclusion/multiple/a.cc|6|first defined here|
obj/Debug/main.o||In function `main':|
/home/ruben/Proyectos/multiple_inclusion/multiple/main.cc|9|multiple definition of `var'|
obj/Debug/a.o:/home/ruben/Proyectos/multiple_inclusion/multiple/a.cc|6|first defined here|
||=== Build finished: 4 errors, 0 warnings ===|
If I try declaring var as a static variable, its value is not modified and so the output is as follows:
> 0
> 0
How should I solve the problem? Thanks a lot in advance.
When you declare a variable in a header file, such as what you've done in memory.h, every source file that includes that header, either directly or indirectly, gets its own separate copy of the variable. Then when you go to link all the .o files together, the linker sees that the variable is instantiated in a bunch of .o files.
Make it extern in the header file and instantiate it in memory.cpp.