Declaration and initialization of global variable

Viewed 46

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.

2 Answers

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.

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
Related