C 预处理器令人困惑的行为

标签 c c-preprocessor

我已将代码 Aplicacion.c 缩小为以下最小表达式:

#if MIVAR == pirulo
#include "a_file.h"
#elif MIVAR == pepe
#include "b_file.h"
#endif

如果我使用gcc -DMIVAR=pepe Aplicacion.c进行编译,我想它会尝试包含b_file.h,但我收到以下错误:

Aplicacion.c:4:10: fatal error: a_file.h: No such file or directory
#include "a_file.h"
          ^~~~~~~~~~

Even if I define inside the source:

#define MIVAR pepe

#if MIVAR == pirulo
#include "a_file.h"
#elif MIVAR == pepe
#include "b_file.h"
#endif

当我执行gcc Aplicacion.c(或gcc -E Aplicacion.c)时,我仍然遇到相同的错误。

我觉得这应该是显而易见的,但我无法找出发生了什么。

有什么想法吗?

(所有这一切都发生在 Ubuntu 中)

最佳答案

C 预处理器将任何未定义的标识符视为 0。所以这个

#if MIVAR == pirulo

看起来像预处理器的#if 0 == 0。即使你定义了它

#define MIVAR pepe

仍然,它尝试将 pepepirulo 进行比较,两者均未定义,因此将它们视为 0。


要解决此问题,您可以定义变量并将其与数字进行比较。

#define pirulo 5
#define pepe 9
#define MIVAR pepe

关于C 预处理器令人困惑的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62705597/

相关文章:

c - ifndef 问题,警告 [Pe014] : extra text after expected end of preprocessing directive

c - 头文件中定义的数组,c 文件中未知的数组

preprocessor - 测试空宏定义

C++ 预处理器连接

c - 基于先前值的 X-macro 枚举

c++ - 使用 C 或 C++ 复制非文本文件?

c - 使物理地址区域中的虚拟地址连续如何提高性能?

c - 如何将后台进程移动到前台

c - 为什么这个段错误在构建之间不一致?

c - 在 C 中迭代地反转字符串