我有一个文件使用了我无法控制的包含中的 FLAGS
宏。 FLAGS
中的内容不一致。有时我需要更改 FLAGS
以向其添加标志。现在我知道我不能执行 #define FLAGS FLAGS|MY_FLAG
,但我想如果我将 FLAGS
存储在一个临时变量中,然后我可以取消定义它并重新定义它使用临时和我的标志。例如:
// Assume this next line is what's in the include file
#define FLAGS (1|2|4)
// The rest of this is source, assume compile with -DMOD
#ifdef MOD
#define TEMP (FLAGS|8)
#undef FLAGS
#define FLAGS TEMP
#endif
int main()
{
printf("0x%x\n", FLAGS);
}
如果定义了 MOD
,则错误为 error: 'FLAGS' was not declared in this scope
。我知道我可以将所有使用 FLAGS
的实际 C 代码更改为使用 FLAGS|MY_FLAG
但我希望修改宏而不是所有代码。
最佳答案
你唯一真正的方法就是定义一个额外的宏
// Assume this next line is what's in the include file
#define FLAGS_FOR_A (1|2|4)
#define FLAGS FLAGS_FOR_A
// The rest of this is source, assume compile with -DMOD
#ifdef MOD
#undef FLAGS
#define FLAGS ( FLAGS_FOR_A | 8 )
#endif
int main()
{
printf("0x%x\n", FLAGS);
}
宏只是做简单的文本替换,在运行前计算
关于c - C 中自引用宏的任何解决方法?我想附加到一个宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27684030/