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

爷,独闯天下 提交于 2019-12-05 08:27:56

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

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!