关于Glog中宏定义的一点引申

下文均在Windows环境下:

编译Glog

在Github上下载Glog源码,并解压到指定目录,打开Cmake工具:

  1. 指定source code目录和build目录;
  2. 点击Configure,会有提示选择VS的版本,以及生成的位数win32 & x64,根据需要选择正确条目。
  3. 点击Finish,开始Configure;
  4. Generate之前,若需要生成动态库dll,需要选择BUILD_SHARED_LIBS;若生成静态库则不需要选择直接下一步即可;
  5. 开始Generate,在build目录中生成大量的文件和glog.sln;
  6. 使用上述步骤2中指定的vs版本开发glog.sln;
  7. 重新生成解决方案,得到指定版本的lib和dll。

配置Visual Studio

  1. 添加头文件路径,即包含目录,glog源码文件夹下glog-xxx/src/window就是需要引用的包含目录。
  2. 添加库路径,glog源码文件夹下glog-0xxx/build/debug即所需要引用的库目录,更准确的说即放置dll和lib所在的目录,注意版本对应;
  3. 添加项目右键属性->c/c++>预处理器:GLOG_NO_ABBREVIATED_SEVERITIES
  4. 添加项目右键属性->链接器->输入->附加依赖项:glogd.lib(debug) 或glod.lib(release)注意版本对应。

实际使用

标准写法

  1. #include<glog\logging.h>  
  2.     
  3. int main()  
  4. {  
  5.     google::InitGoogleLogging("glogtest");//初始化glog结构  
  6.     google::SetLogDestination(google::GLOG_INFO, ".\\log\\info");//指定存放路径  
  7.     LOG(INFO) << "this is a test info message!";//LOG(level)<<stream;level为预设的警告级别,stream为内容  
  8.     google::ShutdownGoogleLogging();//关闭日志  
  9.     return 0;  
  10. }  

引申一点

某些情况下,为了效率,需要能够控制是否输出Log,在这里Glog官方提供了一个方法也就是:DLOG,在debug时正常编译输出,release时不编译。

假如不希望通过是否debug,即有无NDEBUG这个宏定义进行控制,而是希望自定义宏XXX_ON来控制,则可以参考DLOG的写法(在logging.h)中,如下:

  1. #include<glog\logging.h>  
  2.     
  3. #if XXX_ON  
  4.     #define XXXLOG(severity) LOG(severity)  
  5. #else  // !XXX_ON  
  6.     #define XXXLOG(severity)  \  
  7.     static_cast<void>(0), \  
  8.     true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)  
  9. #endif  
  10.     
  11. int main()  
  12. {  
  13.     google::InitGoogleLogging("glogtest");//初始化glog结构  
  14.     google::SetLogDestination(google::GLOG_INFO, ".\\log\\info");//指定存放路径  
  15.     XXXLOG(INFO) << "this is a test info message!";//LOG(level)<<stream;level为预设的警告级别,stream为内容  
  16.     google::ShutdownGoogleLogging();//关闭日志  
  17.     return 0;  
  18. }  

这里#else之后的内容稍微复杂,解释一下:

  1. #define XXXLOG(severity) true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)  
  2. XXXLOG(INFO) << "this is a test info message!";  
  3. //展开  
  4. true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)<< "this is a test info message!";  
  5. //由于LogMessageVoidify()// This has to be an operator with a precedence lower than << but higher than ?:  
  6. //用来去除编译警告,可以忽略,则有如下  
  7. true ? (void) 0 : LOG(severity)<< "this is a test info message!";  
  8. //  
  9. (void) 0  

本质上是一个条件运算符?:,当?前条件为真时,执行:之前的内容,否则执行:之后的内容。

posted @ 2020-12-13 19:44  Didea  阅读(249)  评论(0编辑  收藏  举报