c++variablesglobal-variables

C++ Global variable declaration


What I want to do is just define a variable in a header file and use it in two different cpp files without redefining that variable each time I include that header.

Here is how I tried:

Variables.h

#ifndef VARIABLES_H // header guards
#define VARIABLES_H

static bool bShouldRegister;

#endif

(I also tried extern but nothing changed)

And in a cpp file I give it a value ::bShouldRegister = true or bShouldRegister = true;

In my other cpp file I check it's value by creating a thread and checking its value in a loop (and yes my thread function works well)

 while (true)
 {
     if (::bShouldRegister) // Or if (bShouldRegister)
        {
            MessageBox(NULL,"Value Changed","Done",MB_OK|MB_ICONINFORMATION);
        }
  Sleep(100);
 }

And yes, that MessageBox never appears (bShouldRegister never gets set to true :/)


Solution

  • You should use extern otherwise you will have separated bShouldRegister variables in each translation unit with probably different values.

    Put this in a header file (.h):

    extern bool bShouldRegister;
    

    Put this in one of implementation files (.cpp):

    bool bShouldRegister;
    

    Another way which is simpler is to use inline keyword. Put you variable in a header file as below:

    inline bool bShouldRegister;