Including files causes multiple definition errors for globals

133 Views Asked by At

I am getting a funky multiple definition error. The include structure is as follows:

MAIN -> VM -> BACKEND

Main includes vm which includes backend.

I have three global char * pointers in backend, and it is the members that I get the multiple definition errors.

I get multiple definitions in vm.cpp, main.cpp and moc_vm.cpp (I use Qt).

I tried declaring the pointers as external in the rest of the sources, but it didn't help. All preprocessor guards are in place, and I don't know why I am getting the error, since they are obviously defined in only one place...

Any ideas?

EDIT: This is strange, I can include BACKEND into MAIN and there are no problems, only when the chain is MAIN>VM>BACKEND I get the errors.

3

There are 3 best solutions below

0
On

Define them as external in the header file. Define them (not as external) once in a single cpp file.

You should be safe.

3
On

Use extern char *name; and then in ONE of your .cpp files have char *name = "Something";.

4
On

Solved by changing the pointers to static so they are not linked externally. They are not accessed in any other source anyway. So it was a linkage issue after all...