How can I check if a library is available before c

2019-04-30 03:03发布

问题:

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

Is there a way to do this verification?

回答1:

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.