4

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.

:(?

UberJumper
  • 20,245
  • 19
  • 69
  • 87

3 Answers3

10

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.

  • It's an MS specific extention to do with the C++ name mangling when the function is exported from a library. – Martin Beckett Oct 16 '09 at 15:14
  • Does it need to go in both the header file and the declaration? I don't want to give some wrong information. Thanks. –  Oct 16 '09 at 15:16
  • In my experience the macro 'DLL_EXPORT' is usually used to define the '__declspec(dllexport)' for Microsoft compilers. #if defined(WIN32) #define DLL_EXPORT __declspec(dllexport) #else #define DLL_EXPORT #endif Without the '__declspec(dllexport)' the compiler will not make the variable visible in a dll. It is not needed outside the header file. – gnash117 Mar 28 '13 at 16:32
2

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
  • 219,715
  • 46
  • 258
  • 445
0

When you want to share a global variable among several source files in C++, you need to declare them only in one header file (.h) as

extern  typeName variableName;

And also only the corresponding source file (.cpp) should contain the definition

typeName variableName;

The extern keyword is required to distinguish the declaration from the definition.

Kamran Bigdely
  • 7,946
  • 18
  • 66
  • 86