有没有办法检查一个宏是否已定义并且它同时等于某个值 [英] Is there a way to both check a macro is defined and it equals a certain value at the same time
问题描述
我经常在 C 代码中使用类似对象的预处理器宏作为布尔标志来打开和关闭代码部分.
I regularly use object-like preprocessor macros as boolean flags in C code to turn on and off sections of code.
例如
#define DEBUG_PRINT 1
然后像这样使用它
#if(DEBUG_PRINT == 1)
printf("%s", "Testing");
#endif
但是,如果忘记将包含 #define
的头文件包含在源代码中,则会出现问题.由于未声明宏,预处理器将其视为等于 0,并且 #if
语句永远不会运行.
However, it comes a problem if the header file that contains the #define
is forgotten to be included in the source code. Since the macro is not declared, the preprocessor treats it as if it equals 0, and the #if
statement never runs.
当忘记包含头文件时,可能会出现意想不到的、不守规矩的行为.
When the header file is forgotten to be included, non-expected, unruly behaviour can occur.
理想情况下,我希望能够在一行中检查是否定义了宏,并检查它是否等于某个值.如果未定义,预处理器会抛出错误(或警告).
Ideally, I would like to be able to both check that a macro is defined, and check that it equals a certain value, in one line. If it is not defined, the preprocessor throws an error (or warning).
我正在寻找类似的东西:
I'm looking for something along the lines of:
#if-def-and-true-else-throw-error(DEBUG_PRINT)
...
#endif
就像#ifdef
和#if
的组合,如果不存在就使用#error
.
It's like a combination of #ifdef
and #if
, and if it doesn't exist, uses #error
.
我已经探索了一些途径,但是,预处理器指令不能在 #define
块内使用,据我所知,没有预处理器选项可以抛出错误/警告如果在 #if
语句中使用时未定义宏.
I have explored a few avenues, however, preprocessor directives can't be used inside a #define
block, and as far as I can tell, there is no preprocessor option to throw errors/warnings if a macro is not defined when used inside a #if
statement.
推荐答案
这可能不适用于一般情况(我认为您的要求没有通用解决方案),但对于您的具体示例,您可能会考虑更改此代码序列:
This may not work for the general case (I don't think there's a general solution to what you're asking for), but for your specific example you might consider changing this sequence of code:
#if(DEBUG_PRINT == 1)
printf("%s", "Testing");
#endif
到:
if (DEBUG_PRINT == 1) {
printf("%s", "Testing");
}
如果未定义 DEBUG_PRINT
或将其定义为无法与 1
比较的内容,则它不再冗长并且将无法编译.
It's no more verbose and will fail to compile if DEBUG_PRINT
is not defined or if it's defined to be something that cannot be compared with 1
.
这篇关于有没有办法检查一个宏是否已定义并且它同时等于某个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!