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 :
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 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); } Sleep(100); }
And yes, that MessageBox never appears (bShouldRegister never gets true :/)
The C language allows the redeclaration of the global variable. It means that this variable can get declared again when the first declaration doesn't lead to the initialization of the variable. It is possible because the second program works pretty well in the C language even if the first one fails during compilation.
Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.
The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.
What is a global variable? A variable declared outside of a function is known as a global variable. The scope of the global variable is throughout the program, i.e. all the functions that are declared in multiple files can access it.
You must 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;
If you can use C++17, consider using an inline variable:
// in a header file inline bool bShouldRegister = true;
See How do inline variables work? for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With