I have a header file that has some static variables for all of my files to use. I have a boolean variable in there initialized to 0 –
//in utility.h
static bool read_mess = false;
that I want to change to true if –view-read-messages is in the command line arguments so that I can do something like this when I get a message from a client –
//code from a different file
if(UTILITY_H::read_mess)
std::cout<<"\nMessage successfully received from Client 2: "<<in2;
In main, I check for the command line argument and set the variable, read_mess, to true –
//this is in a for, where temp is the command line arg[i]
else if(strcmp(temp.c_str(), "--view-read-messages") == 0) {
UTILITY_H::read_mess = true;
}
I can print the value of read_mess after this line in main and it says that it is true. But when I’m checking if its true in the if statement I posted above, read_mess is back to false. Why does this happen? I’m sure its just something simple, but I can’t seem to make it work. Are all of the variables in utility.h reinitialized each time I do UTILITY_H::? And if so, why?
staticin this context means “local” (to the translation unit). There will be multiple copies ofread_messin your program, one per translation unit which is not the same thing as a header file. (In your case you can most likely approximate “translation unit” as .cpp or .c or .cc file).Probably what you meant to do was to declare an
externvariable, orstaticclass member and define it in just one translation unit.In practice using
externmeans in your header file you want to write:But in one and only one other place that isn’t a header: