I am trying to create a dynamic library from various .cpp files sharing the same .h. It's something like this:
// mylib1.cpp
namespace mylib {
namespace part1 {
void init() {
part1::commonvar = true;
}
}
}
and
// mylib2.cpp
namespace mylib {
namespace part2 {
void check() {
if (part1::commonvar == true) {
// do something
}
}
}
}
and this is the common header
// mylib.h
#ifdef __cplusplus
extern "C" {
#endif
namespace mylib {
namespace part1 {
bool commonvar = false;
void init();
}
namespace part2 {
void check();
}
}
#ifdef __cplusplus
}
#endif
I am using GCC (MingW) to compile and link this into a single DLL like this:
g++ -Wall -s -O2 -c mylib1.cpp -o mylib1.o
g++ -Wall -s -O2 -c mylib2.cpp -o mylib2.o
g++ -Wall -s -O2 -shared -o MyLib.dll -Wl,--out-implib=lib/libMyLib.dll.a mylib1.o mylib2.o
So, my problem is that when I do all this I get multiple definition error for that variable, when trying to link those two objects. So, I wonder if there's a workaround to make commonvar be common for both namespaces, but not duplicated in both object files. I can make it a member of the namespace "mylib", if necessary, and I can use pre-processor commands, too.
Thanks for your help