C++ variable redefinition

okami picture okami · Oct 1, 2010 · Viewed 7.4k times · Source

I have a file:

variableinclude.h

#ifndef _variableinclude_h_
#define _variableinclude_h_

AClass* variable1;
int* variable2;

#endif

But I include this file in another two different ones:

- atest1.h

- atest2.h

The problem is the following: variable redefinition.

How to avoid that???

Answer

Chubsdad picture Chubsdad · Oct 1, 2010

EDIT2:

Welcome to ODR

EDIT 1:

Make the variables extern in the header file.

extern AClass* variable1;   // assuming AClass is declared at this point.
extern int* variable2;

Define them once and only once in any cpp file e.g. in main.cpp at namespace scope.

AClass* variable1 = NULL;   // assuming AClass is declared at this point.
int* variable2 = NULL;