Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

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 :/)

like image 802
Shahriyar Avatar asked Nov 12 '13 12:11

Shahriyar


People also ask

Can you declare global variables in C?

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.

What is global variable declaration in C?

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.

Where do you declare global variables in C?

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 global variable in C with example?

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.


2 Answers

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; 
like image 167
masoud Avatar answered Oct 16 '22 23:10

masoud


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.

like image 26
bcd Avatar answered Oct 17 '22 01:10

bcd