我有以下代码
#define PROC_ADD
void main(void)
{
while(1)
{
#ifdef PROC_ADD
// Do this code here then undefined it to run the code in the else
// processing work
#undef PROC_ADD
#else
// now that PROC_ADD has been undefined run this code
// processing work
#endif
}
}但是,它将运行代码。但是在未定义PROC_ADD之后,它不会运行else中的代码。
我认为原因可能是您只能在编译时定义和取消定义,而不能在运行时定义。然而,我不是很确定。
发布于 2009-11-26 15:48:34
您所做的构建时间相当于:
int x = 1;
int main()
{
if (x)
{
...
x = 0;
}
else
{
...
}
}ifdef等在构建时发生,但对于您的示例来说,这不是问题。一旦您评估了if (运行时或构建时表单),就可以决定采用哪个分支。在做出决定后更改某些内容并不会改变该决定。
发布于 2009-11-26 15:38:16
#define%s仅在预处理期间起作用。所以
#define PROC_ADD
void main(void)
{
#ifdef PROC_ADD
// Do this code here then undefined it to run the code in the else
// processing work
#undef PROC_ADD
#else
// now that PROC_ADD has been undefined run this code
// processing work
#endif
}由于PROC_ADDR是定义的,所以预处理器将完全排除#else分支,然后执行#undef,因此#else分支代码永远不会在预处理过程中幸存下来,也永远不会到达编译器。
发布于 2009-11-26 15:38:59
当预处理器到达ifdef条件时,将对其求值。当您在ifdef'd代码中使用undef PROC_ADD时,预处理器已经决定了要包括和忽略的代码段。
此外,是的:ifdef、undef等是在预处理时处理的--编译器甚至看不到这些所谓的指令。当然,这也意味着运行时代码永远看不到这些指令。
编辑:预处理器通过对文本文件执行一次遍历来工作。预处理器甚至不关心你的文本文件是否包含C代码!它不知道你的ifdef和else以及其他什么东西恰好在一个while循环中。
https://stackoverflow.com/questions/1802107
复制相似问题