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

拜拜、爱过 提交于 2019-12-07 06:44:44

问题


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.



来源:https://stackoverflow.com/questions/50457326/how-can-i-check-if-a-library-is-available-before-compiling-a-c-program

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