-2

Maybe it is base knowledge, I am apologize.

I have a header file CTemp.h, with namespace CTemp:

namespace CTemp { bool bFlag; }; #ifndef _CTEMP #define _CTEMP bool CTemp::bFlag = true; #endif 

and if I include CTemp.h to my cpp file and try to use CTemp::bFlag

bool bb = CTemp::bFlag; 

the compiler throw error "redefinition"

I surely know, that I should to put initialization to a .cpp file, but I find some way, to solve it only with .h file. Because I don't want to add the .cpp file to my project. I thought, I could solve it with preprocessor directives #ifdef....

Thanks for advice.

4

2 Answers 2

3

In the header file you should only declare the variable:

#ifndef CTEMP_H #define CTEMP_H namespace CTemp { extern bool bFlag; // Need extern to only declare the variable } #endif // CTEMP_H 

Then in one single source file you define the variable with its initialization:

#include "ctemp.h" bool CTemp::bFlag = true; 

Alternatively define the variable as inline:

#ifndef CTEMP_H #define CTEMP_H namespace CTemp { inline bool bFlag = true; } #endif // CTEMP_H 

Now you should not define the variable in a source file.

Sign up to request clarification or add additional context in comments.

2 Comments

But inline bFlag will not be global, isn't it?
@MichalHadraba Who said that? With C++17, you can use inline and bFlag will still be global as shown in this answer. Also the exact same thing is explained here: How can I call a method of a variable, which contains in a namespace? in the dupe. See method 2 of the above linked answer.
0

The problem is that both bool bFlag and bool CTemp::bFlag = true; are definitions. In other words, you're defining bFlag for the second time when you wrote: bool bFlag = true;.

namespace CTemp { bool bFlag; //this is a definition for the first time }; #ifndef _CTEMP #define _CTEMP bool CTemp::bFlag = true; //this is also a definition but for the second time and hence the error 

Solution

To solve this you can use the extern keyword:

someheader.h

#ifndef _CTEMP #define _CTEMP namespace CTemp { extern bool bFlag; //this is a declaration and not a definition }; #endif 

somesource.cpp

#include "someheader.h" bool CTemp::bFlag = true; //this is a definition 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.