在 C++ 中使用静态变量作为日志开关

Using static variables as a logging switch in C++

main.cpp 有很多 Log 点缀在任何地方:

#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");  
}

并且 LogClass 在 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;
}

我想我可以在 main.cpp 中做到这一点:

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

*上面的代码实际上给出了一个错误:redefinition of ‘bool util::LogClass::LOG_ENABLED’ 布尔 util::LogClass::LOG_ENABLE=假 *

但是,如果我将它移到主体中:

#include "utils.cpp"  

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

然后代码可以正常编译。所以我的问题是为什么我不能在 main() 函数之外启用它,即使它是静态成员,为什么 (g++) 编译器将它作为重新定义?

您只能在定义变量时静态初始化变量。 main函数里面的初始化是动态的,没问题

我同意编译器错误很奇怪 - 编译器可能会尝试自动扣除应该存在的 "missing" 类型以进行重新定义。