Global declaration in global header file?

I have a header file, say, Common.h, which is included in all files for several projects. Basically I want to declare a global variable, for example:

class MemoryManager; DLL_EXPORT MemoryManager* gMemoryManager; 

When I do this, I get tons of linker errors saying

the class MemoryManager * gMemoryManager is already defined.

: (

+4
c ++
source share
3 answers

Since you are creating a separate copy of the variable in each compiled file. Then they collide at the binding stage. Remember that the preprocessor reads in all header files and makes one large file of them. Therefore, every time this large file is compiled, another identical copy of gMemoryManager .

You need to use extern and define it in a single file without a header.

In your header file

 extern DLL_EXPORT MemoryManager* gMemoryManager; 

In one of your C ++ files

 DLL_EXPORT MemoryManager * gMemoryManager; 

By the way, I don’t know what DLL_EXPORT does, I just assume that it needs to go in both places.

+10
source share

it

 MemoryManager* gMemoryManager; 

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

 extern DLL_EXPORT MemoryManager* gMemoryManager; 

and put the definition in one cpp file.

+2
source share

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

 extern typeName variableName; 

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

 typeName variableName; 

The extern keyword is required to distinguish an ad from a definition.

0
source share

All Articles