Search code examples
c++staticg++static-methods

Using static variables as a logging switch in C++


There's the main.cpp that has lots of Log prinkled wherever:

#include "utils.hpp"
...//some code  
int main(){
 int a = 0;
 int b = 0;
 util::LogClass::Log("Initial","something);  

 //some more code 
 util::LogClass::Log("Mid","something");  

 //some more code  
 util::LogClass::Log("Middle","something");  
}

And the LogClass is defined like this in utils.hpp:

namespace util{
 class LogClass{
     public:static bool LOG_ENABLED;
     public: static void Log(std::string tag, std::string message){
      if(LOG_ENABLED){
      std::cerr << tag+": "+message <<std::endl;}
    }
  }
  bool LogClass::LOG_ENABLED=true;
}

I was thinking I would be able to do this in main.cpp:

#include "utils.cpp"  
util::LogClass::LOG_ENABLE=false;
int main(){ //the previous main function}  

*the above code actuallly gives an error saying: redefinition of ‘bool util::LogClass::LOG_ENABLED’ bool util::LogClass::LOG_ENABLE=false *

but, if I move it inside the main:

#include "utils.cpp"  

int main(){ util::LogClass::LOG_ENABLED=false; //the previous main function}    

then the code compiles fine. So my question is why can't I enable it outside the main() function even if it is a static member, and why does the (g++) compiler takes it as a redefinition?


Solution

  • You can only statically initialize a variable at the point where it is getting defined. The initialization inside the main function is dynamic, so that's fine.

    I agree that the compiler error is weird though - the compiler might be trying to auto-deduct the "missing" type that should be there for a redefinition.