简体   繁体   English

在编译C程序之前,如何检查库是否可用

[英]How can I check if a library is available before compiling a C program

Is there a way to include a library only if it is available to the compiler? 有没有办法只在编译器可用时才包含库?

I thought about checking it with #ifndef (as shown below) but it just checks if a macro name is not defined and what I really need is to check if the compiler can reach to a C library in the compilation time. 我考虑用#ifndef检查它(如下所示),但它只检查是否未定义宏名称,我真正需要检查编译器是否可以在编译时到达C库。

#ifndef _MY_LIBRARY_H
    #include "my_library.h"
#endif

Is there a way to do this verification? 有没有办法进行此验证?

Clang and GCC have had a __has_include macro for a very long time, which you can use like this: Clang和GCC在很长一段时间内都有一个__has_include ,你可以像这样使用它:

#if __has_include("my_library.h")
    #include "my_library.h"
#endif

It works with angle brackets too (in fact, it works with anything that you can pass to #include ): 它也适用于尖括号(事实上,它适用于你可以传递给#include任何东西):

#if __has_include(<my_library.h>)
    #include <my_library.h>
#endif

__has_include has recently been anointed standard C++17 , meaning that C++ compilers that don't support it now will most likely have it in a not-too-distant feature. __has_include最近被__has_include 标准C ++ 17 ,这意味着现在不支持它的C ++编译器很可能会在一个不太远的特性中使用它。 Since it's a preprocessor feature, C compilers that belong to the same suite as a C++ compiler have a high chance of getting the feature by osmosis as well. 由于它是预处理器功能,因此与C ++编译器属于同一套件的C编译器也很有可能通过渗透来获得该功能。

Still, note that while __has_include will tell you if the header file is present, it won't save you from eventual linker errors in the case of a broken installation. 但请注意,虽然__has_include将告诉您头文件是否存在,但在安装中断的情况下,它不会使您免于最终的链接器错误。

The old-fashioned way to do this is to have a pre-build script that tries to compile #include "my_library.h" , and output a configuration file with #define HAS_LIBRARY_SOMETHING to 0 or 1 depending on the result of that operation. 执行此操作的传统方法是使用预构建脚本尝试编译#include "my_library.h" ,并将#define HAS_LIBRARY_SOMETHING的配置文件输出为0或1,具体取决于该操作的结果。 This is the approach that programs like autoconf deploy. 这是autoconf部署程序的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM