【发布时间】:2023-04-11 00:33:01
【问题描述】:
我正在编写一个简单的日志库,并尝试在日志级别上设置编译时间定义。如果我将 #define LOG_COMPILE_MIN_LEVEL 放在头文件中,则不会在编译时设置它,但是如果 #define LOG_COMPILE_MIN_LEVEL 在 c 文件中,它确实可以工作。
这里是相关部分的sn-ps
CMakeLists.txt
// Trying to set LOG_COMPILE_MIN_LEVEL to ERROR
add_definitions(-DLOG_COMPILE_MIN_LEVEL=ERROR)
# I have also tried
add_compile_definitions(LOG_COMPILE_MIN_LEVEL=ERROR)
在log.h
// I define in this file the following (technically they are enums with values set)
// DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3
// By default resort to INFO if not found
#ifndef LOG_COMPILE_MIN_LEVEL
#define LOG_COMPILE_MIN_LEVEL INFO
#endif
// In log.h I am trying to do this, where before even going to
// the log function (log_log) the level is checked against the compile level
// So since I (in theory) set LOG_COMPILE_MIN_LEVEL to ERROR, any INFO levels
// are not logged since INFO (value of 1) is below LOG_COMPILE_MIN_LEVEL which is
// set to ERROR (value of 3)
// Ideally/in theory the compiler will compile out any messages not used by doing this....
#define LOG(level, __FILENAME__, __LINE__, ...) \
if (level < LOG_COMPILE_MIN_LEVEL);\
else log_log(level, __FILENAME__, __LINE__, __VA_ARGS__)
// The reason for having LOG and LOG_COMPILE_MIN_LEVEL in the header is cause I provide
// some logging macros like:
#define LOG_ERROR(...) LOG(ERROR, __FILENAME__, __LINE__, __VA_ARGS__)
// In some c/cpp file, this should not work since log level is set to
// ERROR but it does (because the default value of LOG_COMPILE_MIN_LEVEL is
// info.
LOG_INFO("My info message);
无论我在 CMakeLists.txt 中尝试过什么,我都无法让它工作。现在当我移动时
#ifndef LOG_COMPILE_MIN_LEVEL
#define LOG_COMPILE_MIN_LEVEL INFO
#endif
对于 c/cpp 文件,它确实有效(设置为 ERROR)。
- 为什么?
- 发生了什么?
- 头文件如何设置?
我试图在头文件中设置/定义它的原因是#define LOG 方法。
【问题讨论】:
-
请发布完整的minimal reproducible example。
LOG_INFO未定义。 -
您不能为头文件指定传递给编译器的编译定义(至少不能通过常规编译),因为您传递 C/CPP 源文件,因此每次您都需要使用这些编译定义编译一个包含
log.h的文件,即使它是间接编译的。不确定您的情况出了什么问题,因为既没有显示行为的源文件,也没有用于创建问题中显示的构建系统的CMakeLists.txt文件。