C预处理器能否检测到无法找到头文件并发出特定警告?

Rob*_*tin 9 include c-preprocessor

我有一个需要特定头文件的C文件.如果该头文件不存在,我希望预处理器发出特定的警告.就像是:

#if !(#include <special.h>)
#warning "Don't worry, you can fix this."
#warning "You just need to update this other repo over here:"
#endif
Run Code Online (Sandbox Code Playgroud)

这可能与C预处理器一起使用吗?

Vik*_*Vik 16

我知道这是一个老问题,但我也需要一种方法来做这个,当我读到这些答案时我很失望.事实证明,clang有一个很好的__has_include("header name")指令可以完美地运行你需要的东西:)也许你想通过调用来检查指令是否可用#if defined(__has_include)

  • [gcc也有这个](https://gcc.gnu.org/gcc-5/changes.html).它说gcc 5,但4.9似乎对我来说很好. (5认同)

IPr*_*ory 9

您可以随时检查#define X包含的文件中的宏是否...已定义:)


Ada*_*eld 8

不,这是不可能的.你所能做的只是尝试#include标题,如果它不存在,编译器会给你一个错误.

另一种方法是使用像GNU autoconf这样的工具.autoconf生成一个shell脚本configure,该脚本分析您的构建系统,并确定是否安装了某些头文件,并生成一个由指示该信息的宏组成的头文件.

例如,它可能会定义HAVE_SYS_TIME_H您的构建系统是否包含标头<sys/time.h>,因此您可以编写如下代码:

#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#warning "Don't worry, you can fix this."
#endif
Run Code Online (Sandbox Code Playgroud)