UberJumper
UberJumper

Reputation: 21145

Declaring a global in a global header file?

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.

:(?

Upvotes: 4

Views: 5050

Answers (3)

Kamran Bigdely
Kamran Bigdely

Reputation: 8446

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.

Upvotes: 0

user181548
user181548

Reputation:

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.

Upvotes: 10

sbi
sbi

Reputation: 224009

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.

Upvotes: 2

Related Questions