【问题标题】:Can't use "__has_include" preprocessor in Keil IDE无法在 Keil IDE 中使用“__has_include”预处理器
【发布时间】: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


【解决方案1】:

有什么建议吗?

不要使用像__has_include 这样的不可移植的扩展。构建系统用于检测有关环境的信息,例如可用的标头。

例如,CMake 构建系统有check_include_file,您可以检查包含文件是否存在。然后如果包含文件Debugg.h(为什么大写+小写混合?)存在,则在编译中添加一个宏HAS_DEBUGG_H,如果定义了该宏,则包含头文件。

一个 libX.c、一个 libX.h 和 libX_conf.h 文件。检查 Debugg.h 在配置文件中。如果可用,它会检查特定线程的打印。如果不是,则禁用调试

这应该用宏来完成,而不是“检测头文件”。应该有一个宏,称为LIBX_DEBUG_ENABLE,如果定义,libX 应该输出调试信息。 IE。这是使用宏完成的用户配置设置,而不是删除文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-21
    • 2016-12-26
    • 2017-10-27
    • 2017-02-11
    • 2019-06-26
    • 2018-10-11
    • 2021-12-29
    • 2021-05-25
    相关资源
    最近更新 更多