Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand static boolean behavior

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?

like image 623
Sterling Avatar asked Sep 19 '11 18:09

Sterling


1 Answers

static in this context means "local" (to the translation unit). There will be multiple copies of read_mess in 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 extern variable, or static class member and define it in just one translation unit.

In practice using extern means in your header file you want to write:

extern bool read_mess;

But in one and only one other place that isn't a header:

bool read_mess = false;
like image 90
Flexo Avatar answered Oct 04 '22 06:10

Flexo