tags:

views:

104

answers:

2

I have a header file, lets say Common.h, that is included in all of the files over several projects. Basically i want to declare a global variable, e.g.:

class MemoryManager;
DLL_EXPORT MemoryManager* gMemoryManager;

When i do this i get tons of linker errors saying

class MemoryManager* gMemoryManager is already defined.

:(?

+6  A: 

As it is you are creating a separate copy of the variable in each compiled file. These are then colliding at the linking stage. Remember that the preprocessor reads in all the header files and makes one big file out of all of them. So each time this big file is compiled, another identical copy of gMemoryManager is created.

You need to use extern and define it in one non-header file.

In your header file

extern DLL_EXPORT MemoryManager* gMemoryManager;

In one of your C++ files

DLL_EXPORT MemoryManager * gMemoryManager;

By the way I have no idea what DLL_EXPORT does, I am just assuming it needs to go in both places.

Kinopiko
It's an MS specific extention to do with the C++ name mangling when the function is exported from a library.
Martin Beckett
Does it need to go in both the header file and the declaration? I don't want to give some wrong information. Thanks.
Kinopiko
+1  A: 

This

MemoryManager* gMemoryManager;

defines a variable. If you do this in a header, the variable will be defined in each translation unit that includes that header, hence the linker errors. If you want to declare a variable, do it this way:

extern DLL_EXPORT MemoryManager* gMemoryManager;

and put the definition into exactly one cpp file.

sbi