关于Glog中宏定义的一点引申
下文均在Windows环境下:
编译Glog
在Github上下载Glog源码,并解压到指定目录,打开Cmake工具:
- 指定source code目录和build目录;
- 点击Configure,会有提示选择VS的版本,以及生成的位数win32 & x64,根据需要选择正确条目。
- 点击Finish,开始Configure;
- Generate之前,若需要生成动态库dll,需要选择BUILD_SHARED_LIBS;若生成静态库则不需要选择直接下一步即可;
- 开始Generate,在build目录中生成大量的文件和glog.sln;
- 使用上述步骤2中指定的vs版本开发glog.sln;
- 重新生成解决方案,得到指定版本的lib和dll。
配置Visual Studio
- 添加头文件路径,即包含目录,glog源码文件夹下glog-xxx/src/window就是需要引用的包含目录。
- 添加库路径,glog源码文件夹下glog-0xxx/build/debug即所需要引用的库目录,更准确的说即放置dll和lib所在的目录,注意版本对应;
- 添加项目右键属性->c/c++>预处理器:GLOG_NO_ABBREVIATED_SEVERITIES
- 添加项目右键属性->链接器->输入->附加依赖项:glogd.lib(debug) 或glod.lib(release)注意版本对应。
实际使用
标准写法
- #include<glog\logging.h>
- int main()
- {
- google::InitGoogleLogging("glogtest");//初始化glog结构
- google::SetLogDestination(google::GLOG_INFO, ".\\log\\info");//指定存放路径
- LOG(INFO) << "this is a test info message!";//LOG(level)<<stream;level为预设的警告级别,stream为内容
- google::ShutdownGoogleLogging();//关闭日志
- return 0;
- }
引申一点
某些情况下,为了效率,需要能够控制是否输出Log,在这里Glog官方提供了一个方法也就是:DLOG,在debug时正常编译输出,release时不编译。
假如不希望通过是否debug,即有无NDEBUG这个宏定义进行控制,而是希望自定义宏XXX_ON来控制,则可以参考DLOG的写法(在logging.h)中,如下:
- #include<glog\logging.h>
- #if XXX_ON
- #define XXXLOG(severity) LOG(severity)
- #else // !XXX_ON
- #define XXXLOG(severity) \
- static_cast<void>(0), \
- true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
- #endif
- int main()
- {
- google::InitGoogleLogging("glogtest");//初始化glog结构
- google::SetLogDestination(google::GLOG_INFO, ".\\log\\info");//指定存放路径
- XXXLOG(INFO) << "this is a test info message!";//LOG(level)<<stream;level为预设的警告级别,stream为内容
- google::ShutdownGoogleLogging();//关闭日志
- return 0;
- }
这里#else之后的内容稍微复杂,解释一下:
- #define XXXLOG(severity) true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
- XXXLOG(INFO) << "this is a test info message!";
- //展开
- true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)<< "this is a test info message!";
- //由于LogMessageVoidify()是// This has to be an operator with a precedence lower than << but higher than ?:
- //用来去除编译警告,可以忽略,则有如下
- true ? (void) 0 : LOG(severity)<< "this is a test info message!";
- //即
- (void) 0
本质上是一个条件运算符?:,当?前条件为真时,执行:之前的内容,否则执行:之后的内容。
浙公网安备 33010602011771号