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

发布于 2025-01-08 08:42:17 字数 284 浏览 1 评论 0原文

我有一个需要特定头文件的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

_畞蕅 2025-01-15 08:42:17

我知道这是一个老问题,但我也需要一种方法来做到这一点,当我读到这些答案时我很失望。事实证明,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)

墨小墨 2025-01-15 08:42:17

不,这是不可能的。您所能做的就是尝试#include标头,如果它不存在,编译器会给您一个错误。

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

例如,如果您的构建系统包含标头 ,它可能会定义 HAVE_SYS_TIME_H,这样您就可以编写如下代码:

#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#warning "Don't worry, you can fix this."
#endif

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:

#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#warning "Don't worry, you can fix this."
#endif
柳若烟 2025-01-15 08:42:17

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

You could always check if the #define X macro, from the included file, is ... defined :)

心如荒岛 2025-01-15 08:42:17

如果您需要的只是警告头文件不存在(并且没有自定义代码),那么大多数编译器已经给您一个警告。

$ LC_MESSAGES=en_US gcc -c bar.c
bar.c:1:17: fatal error: foo.h: No such file or directory
compilation terminated.

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.

$ LC_MESSAGES=en_US gcc -c bar.c
bar.c:1:17: fatal error: foo.h: No such file or directory
compilation terminated.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文