如何在编译C程序之前检查库是否可用 [英] How can I check if a library is available before compiling a C program

查看:77
本文介绍了如何在编译C程序之前检查库是否可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否只有在编译器可用的情况下才包含库?

Is there a way to include a library only if it is available to the compiler?

我考虑过用#ifndef进行检查(如下所示),但是它只是检查是否未定义宏名称,而我真正需要的是检查编译器在编译时是否可以访问C库.

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 _MY_LIBRARY_H
    #include "my_library.h"
#endif

是否可以进行此验证?

推荐答案

Clang和GCC的 __has_include很长一段时间,您可以这样使用:

Clang and GCC have had a __has_include macro for a very long time, which you can use like this:

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

它也适用于尖括号(实际上,它适用于您可以传递给#include的任何内容):

It works with angle brackets too (in fact, it works with anything that you can pass to #include):

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

__has_include最近被膏为标准C ++ 17 ,这意味着现在不支持它的C ++编译器很可能会将其包含在一个不太遥远的功能中.由于它是预处理器功能,因此与C ++编译器属于同一套件的C编译器也很有可能通过渗透获得该功能.

__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. 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.

不过,请注意,尽管__has_include会告诉您头文件是否存在,但是如果安装损坏,它不会使您免于最终出现链接器错误.

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.

执行此操作的老式方法是拥有一个预编译脚本,该脚本尝试编译#include "my_library.h",并根据该操作的结果将#define HAS_LIBRARY_SOMETHING的配置文件输出为0或1.这是像autoconf这样的程序部署的方法.

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. This is the approach that programs like autoconf deploy.

这篇关于如何在编译C程序之前检查库是否可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆