C 预处理器能否检测到是否找不到头文件并发出特定警告?
我有一个需要特定头文件的 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
使用 C 预处理器可以实现这一点吗?
I have a C file that needs a specific header file. If that header file does not exist, I want the preprocessor to issue a specific warning. Something like:
#if !(#include <special.h>)
#warning "Don't worry, you can fix this."
#warning "You just need to update this other repo over here:"
#endif
Is this possible with the C preprocessor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我知道这是一个老问题,但我也需要一种方法来做到这一点,当我读到这些答案时我很失望。事实证明,clang 有一个很好的
__has_include("header name")
指令,可以完美地完成您需要的操作:)也许您想首先通过调用#if Defined(__has_include)来检查该指令是否可用
I know this is a old question, but I also needed a way to do this and I was disappointed when I read these answers. It turns out that clang has a nice
__has_include("header name")
directive that works flawlessly to do what you need :)Maybe you want to check if the directive is available first by calling
#if defined(__has_include)
不,这是不可能的。您所能做的就是尝试
#include
标头,如果它不存在,编译器会给您一个错误。另一种方法是使用 GNU autoconf 之类的工具。 autoconf 生成一个名为
configure
的 shell 脚本,它会分析您的构建系统并确定是否安装了某些头文件等信息,并生成一个由指示该信息的宏组成的头文件。例如,如果您的构建系统包含标头
,它可能会定义HAVE_SYS_TIME_H
,这样您就可以编写如下代码:No, this is not possible. All you can do is try to
#include
the header, and if it doesn't exist, the compiler will give you an error.An alternative would be to use a tool like GNU autoconf. autoconf generates a shell script called
configure
which analyzes your build system and determines things like whether or not you have certain header files installed, and it generates a header file consisting of macros indicating that information.For example, it might define
HAVE_SYS_TIME_H
if your build system includes the header<sys/time.h>
, so you can then write code such as:您始终可以检查包含文件中的
#define X
宏是否...已定义:)You could always check if the
#define X
macro, from the included file, is ... defined :)如果您需要的只是警告头文件不存在(并且没有自定义代码),那么大多数编译器已经给您一个警告。
If all you need is a warning that the header file is not there (and no custom code), then most compilers will already give you one.