Shahriyar Shahriyar - 1 year ago 163
C++ Question

C++ Global variable declaration

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

Here is how I tried :

#ifndef VARIABLES_H // header guards

static bool bShouldRegister;


(I also tried extern but nothing changed)

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

In my another cpp file I check it's value by creating a thread and check 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);

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

Answer Source

You must use extern, otherwise you have separate bShouldRegister in each translation unit with probably different values.

Put this in a header file (.h):

extern bool bShouldRegister;


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

bool bShouldRegister;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download