使用C if语句中定义的(MACRO) [英] Using defined(MACRO) inside the C if statement
问题描述
我想在 C 中编写代码,如下所示:
I would like to write code in C something like this:
if(defined(MACRO))
...
else
...
但我找不到任何方法在 C 中执行此操作,因为定义的(MACRO)预处理器操作符仅在#if的内部工作。有没有办法做到这一点?
but I could not find any way to do this in C, since the defined(MACRO) preprocessor operator works only inside #if's. Is there a way to do this?
我真正想要写的是:
What I really like to do is to write:
ASSERT(UART, var >= 0);
其中
where
#define ASSERT(NAME, TEST) \
do { \
if (defined(NAME) && !(TEST)) \
printf("Assert failed"); \
} while(0)
因此我可以在宏定义时打开ASSERT检查,如果不是定义,那么不应该检查断言。如果您尝试这样做,那么您会得到:
thus I could turn on ASSERT checks when a macro is defined and if it is not defined, then the asserts should not be checked. If you try to do this, then you get:
implicit declaration of function `defined'
$ b $因为GCC编译器没有找到 defined()
预处理器运算符,所以这是很容易理解的。
which is quite understandable since the GCC compiler does not find the defined()
preprocessor operator.
推荐答案
将 comex 的宏扩展为如果参数定义为1,则为1。否则将其扩展为0:
A macro by comex is expanded to 1 if the argument is defined to 1. Otherwise it is expanded to 0:
#define is_set(macro) is_set_(macro)
#define macrotest_1 ,
#define is_set_(value) is_set__(macrotest_##value)
#define is_set__(comma) is_set___(comma 1, 0)
#define is_set___(_, v, ...) v
您可以如下使用它:
if (is_set(MACRO)) {
/* Do something when MACRO is set */
}
这篇关于使用C if语句中定义的(MACRO)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!