Reputation: 1
i have some trouble with global variables. My task is to define a global variable in a header file whose value can be updated in other files. If i modify the value of the global variable in a file, i want that this updated value can be seen in all other files.
For example let's say i have 4 files: main.cpp constants.h server.h and server.cpp.
in costants.h i want the global variable of type int call myVar.
static int myVar=0;
in main.cpp i include the header file and i call myFunction that is implemented in server.cpp
#include "constants.h"
cout<<"myVar is:"<<myVar<<"\n"; // prints 0;
myVar=3;
cout<<"now myVar is:"<<myVar<<"\n"; // prints 3;
void myFunction();
in sever.cpp i include the constant header file and implement myFuntion()
#include "constants.h"
void myFunction()
{
cout<<"myVar in server.cpp is:"<<myVar<<"\n"; //prints 0 not 3!!!
}
The problem is that here myVar is 0 while i would like it to be 3!
Upvotes: 0
Views: 6593
Reputation: 37606
If you define your variable as static
it means that the scope of the variable is the file itself, or in other worlds, that there will be a variable created for each file in which you're including your header file. So main.cpp
and server.cpp
will each have their own instance of the myVar
variable.
You can declare a variable in main.cpp
and access this variable using the extern keywords:
// In main.cpp
int myVar = 0;
// In server.cpp
extern int myVar;
Another solution would be to put the extern declartion in your header, so you can access the variable in each file where you include the header. There is no conflict in declaring a variable as extern int var
in a header file and declaring a variable int var
in a file with an include to the header.
Upvotes: 7