Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: static vars not persisting between files

Tags:

c++

I have a config.h file with a bunch of constants. in main.cpp, it sets one of the constants to some value, and then calls a function in util.cpp.

util.cpp also has config.h included, but the variable set by main.cpp does not have the same value.

Code:

config.h:

static int MAX_NUMBER_OF_TRAINING_DATA = 1000;

main.cpp (main):

else if (strcmp(argv[i], "-mTrnData") == 0)
            {
                MAX_NUMBER_OF_TRAINING_DATA = atoi(argv[i + 1]);
            cout << "Number of data sets to be generated: " << MAX_NUMBER_OF_TRAINING_DATA << "\n\n";
                          // prints what I tell it
            }

and in utils.cpp

cout << "Number of data sets generated: " << MAX_NUMBER_OF_TRAINING_DATA << "\n\n";
    // prints the default value (in this case, 1000)

So, how do I fix this so that I can have my config.h file of constants be remembered throughout my cpp files?

In Java, you can do Config.NAME_OF_CONSTANT , so, if there is a way to do that in C++, that would be most grand.

I know constants aren't supposed to change, but the only time they do change is in main() when reading in the arguments from the running the program... after that they don't change.

like image 842
NullVoxPopuli Avatar asked Mar 16 '26 20:03

NullVoxPopuli


1 Answers

Each translation unit receives its own copy of static data.

The easiest way to verify this is to print the address of MAX_NUMBER_OF_TRAINING_DATA in both units - it will be different. To avoid it, declare it extern in the header and define it once in one unit, for example in main.cpp.

Apart from that is it evil to have such global variables (whose naming scheme even suggests that we're talking about constants!). You might consider to refactor the code, for example use a getter GetMaxNumberOfTrainingData() to make the value available while keeping write access to it restricted to a single unit.

like image 160
Alexander Gessler Avatar answered Mar 19 '26 11:03

Alexander Gessler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!