okami
okami

Reputation: 2153

C++ variable redefinition

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???

Upvotes: 1

Views: 10054

Answers (1)

Chubsdad
Chubsdad

Reputation: 25497

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;

Upvotes: 10

Related Questions