aarelovich aarelovich - 1 month ago 6
C++ Question

Why is a globally define static variable being reset?

My code is very large, but I'll try to minimize it here as best as possible.

Basically I want to define a string that is modified in only one place (my main) and then be read in my entire program.

My defines.h is included everywhere so in there I defined.

static std::string MAINLOG = "RANDOMNES";


In my main function I do:

for (int i = 0; i < files.size(); i++){

// Do stuff

prepDbugDir(); // This sets MAINLOG to "CORRECT_VALUE"

std::cout << "Before " << MAINLOG << std::endl;

// Call a class function whose includes include my defines.h

std::cout << "After " << MAINLOG << std::endl;


}


And the print out of my file is

Before CORRECT_VALUE
RANDOMNESS
After CORRECT_VALUE


So my question is why and how can I get the value to be maintained inside my classes.

Answer

Every translation unit (.c or .cpp file, basically) that includes defines.h will have its own copy of the variable.

I believe declaring the global extern in the header

extern std::string MAINLOG;

and then defining it as a non-static global variable in any one of the .c or .cpp files

std::string MAINLOG = "RANDOMNES";

will solve the problem. But it's poor coding style, IMO. The C++ way would be at least a singleton class.

I can't give meaningful names without knowing the context, but the idea is as follows:

mainlog.h

class Mainlog {
   Mainlog() = default; // Private default constructor

   static Mainlog& instance();

public:
   static const std::string& get() {
      return instance().value;
   }

   static void set(const std::string& newValue) {
      instance().value = newValue;
   }

private:
   std::string value {"RANDOMNESS"};
};

mainlog.cpp (don't put this in a header!)

Mainlog& Mainlog::instance() {
      static Mainlog mainlog;
      return mainlog;
   }
Comments