我遇到了奇怪的问题,因为 gcc 预处理器在 #if 指令上失败。
示例代码:
#include "stdio.h"
enum BoardTypes{
Board_IO_WithAdc,
Board_IO_WithEnc,
Board_PakelcIn,
Board_PakelcOutP,
Board_PakelcOutV,
};
#define BoardAdr Board_PakelcIn
int main(void){
#if ((BoardAdr==Board_PakelcOutV) || (BoardAdr==Board_PakelcOutP))
printf("Board_PakelcOutV or Board_PakelcOutP\n");
#endif
#if (BoardAdr==Board_PakelcIn)
printf("Board_PakelcIn\n");
#endif
}
预期结果是Board_PakelcIn,但得到了Board_PakelcOutV或Board_PakelcOutP,Board_PakelcIn。
显然这里出了问题。
所有宏都会扩展为未定义的内容,被视为 0。
预处理器没有你的
enum
的概念,所以你的代码本质上就是:
#include "stdio.h"
#define BoardAdr Board_PakelcIn
int main(void){
#if ((BoardAdr==Board_PakelcOutV) || (BoardAdr==Board_PakelcOutP))
printf("Board_PakelcOutV or Board_PakelcOutP\n");
#endif
#if (BoardAdr==Board_PakelcIn)
printf("Board_PakelcIn\n");
#endif
}
将
BoardAdr
替换为Board_PakelcIn
后,我们得到:
#include "stdio.h"
int main(void){
#if ((Board_PakelcIn==Board_PakelcOutV) || (Board_PakelcIn==Board_PakelcOutP))
printf("Board_PakelcOutV or Board_PakelcOutP\n");
#endif
#if (Board_PakelcIn==Board_PakelcIn)
printf("Board_PakelcIn\n");
#endif
}
现在,所有
Board_PakelcIn
、Board_PakelcOutV
和 Board_PakelcOutP
都未定义,因此 0
,所以我们剩下:
#include "stdio.h"
int main(void){
#if ((0==0) || (0==0))
printf("Board_PakelcOutV or Board_PakelcOutP\n");
#endif
#if (0==0)
printf("Board_PakelcIn\n");
#endif
}