【发布时间】:2012-03-13 05:11:35
【问题描述】:
有没有办法保护宏定义?更具体地考虑以下几点:
#define macro1 x
// code segment 1 involving macro1 goes here
// code segment 2 involving macro1 goes here
// code segment 3 involving macro1 goes here
在示例中,我放置了 3 个 cmets,表示涉及宏的代码段。我现在想做的是能够避免宏影响代码段 2。有没有办法告诉编译器替换段 1 和段 3 中的所有宏 1 实例,而不是段 2 中的所有实例?这是一种可能的方法:
#define macro1 x
// code segment 1 involving macro1 goes here
#undef macro1
// code segment 2 involving macro1 goes here
#define macro1 x
// code segment 3 involving macro1 goes here
缺点是我必须再次定义宏。说我想用这个词 NULL 在我的程序中(不要问我为什么要使用它)。我希望这是一个变量 但在大多数情况下,C 预处理器会将其更改为 0。所以我想做的就是成为 能够在短时间内阻止它,然后让它成为以前的样子。
尝试失败:
让我们假设宏 1 已在外部某处定义,我们甚至不知道该宏的值是什么。我们想要的只是避免让它替换第二段中的内容。
// code segment 1 involving macro1 goes here
#ifdef macro1
#define TEMP macro1
#undef macro1
#endif
// code segment 2 involving macro1 goes here
#ifdef TEMP
#define macro1 TEMP
#undef TEMP
#endif
// code segment 3 involving macro1 goes here
我们的想法是检查宏是否存在,如果存在,那么我们想将值存储到另一个变量中,取消定义宏,最后在需要时再次定义宏。 不幸的是,这段代码不起作用,因为在我们执行代码段 3 之前,macro1 将被替换为 TEMP,而不是 TEMP 应该具有的值。
【问题讨论】:
标签: c++ c c-preprocessor