【发布时间】:2021-08-05 13:32:16
【问题描述】:
我正在使用Keil 为 STM32 微控制器编写代码。在main.h 文件中,我使用以下代码:
#if defined __has_include //Keil recognizes this preprocessor. If it was unavailable, Keil would have marked it as gray
#if __has_include("Debugg.h")
#include "Debugg.h"
#endif
#endif
这会检查Debugg.h 文件是否存在。假设我在Debugg.h 文件中有一个#define:
#define DEBUGGING 1
现在,我希望在main.h 中定义DEBUGGING。再次main.h:
#if defined __has_include //Keil recognizes this preprocessor. If it was unavailable, Keil would have marked it as gray
#if __has_include("Debugg.h")
#include "Debugg.h"
#endif
#endif
#ifdef DEBUGGING
#define MAIN_DEBUG 1 //This line runs
#else
#define MAIN_DEBUG 0 //Keil IDE mark this line as gray, meaning "unavailable code"
#endif
但是,每当我尝试打印MAIN_DEBUG 或使用它时,它都是0!
注意:
似乎 Keil IDE 可以识别 __has_include 预处理器,但编译器不识别;因为当我注释掉这些行时:
//#if defined __has_include
#if __has_include("Debugg.h")
#include "Debugg.h"
#endif
//#endif
我收到以下错误:
compiling main.c...
..\Library\main.h(5): error: #59: function call is not allowed in a constant expression
#if __has_include("Debugg.h")
..\Library\main.h(5): error: #31: expression must have integral type
#if __has_include("Debugg.h")
..\Library\main.c: 0 warnings, 2 errors
我也使用default ARM compiler version 5。有什么建议吗?
谢谢。
【问题讨论】:
-
建议?不要依赖这个非标准的
__has_include()宏。如果您的编译器不支持它,那么无论如何我看不到任何替代方案。大多数 C 语言编写世界都没有这样的功能。 -
@MohammadKholghi 您可以通过在
#if defined __has_include之后插入#error __has_include is defined来检查 -
@MohammadKholghi,IDE不一定使用编译器来确定宏是否已知。甚至可能根本不检查它,可能是因为它的名称形式(前导双下划线将此宏的名称放在为 C 语言实现保留的特殊名称类别中)。但即使有办法告诉编译器识别宏,我的建议仍然是避免使用它。它是非标准的,而且似乎没有提供任何特别有用的东西。
-
@MohammadKholghi,C 源代码中没有标准方法来检查标头是否可用。相反,有一些基于标准语言特性的传统机制,可以通过检查文件是否可用来解决您试图解决的相同问题。例如,大多数编译器允许您在命令行上指定宏定义。
-
你想解决的真正的问题是什么?
标签: c c-preprocessor keil