checking whether library exist via preprocessor

There are two libraries zconf.h and unistd.h which are used to at least to get pid of the process. I generally test my code on Mac OSX and Ubuntu 18.04 in which they use zconf.h preferably(compiler offers zconf.h in lieu of unistd.h) if I forget to add, then if the code works, it's ok. However, in some prior day I needed to test the code in another machine AFAIR it has Ubuntu 10 or 12. Its compiler complained that there is no zconf.h. I wonder whether there is a way to check a machine has zconf.h, if not, use unistd.h. Can it be done using preprocessors like,

#ifdef ITS_IF_CONDITION
    #include <zconf.h>
#else
    #include <unistd.h>

Upvotes: 0

Views: 928

Answers (1)

cyco130
cyco130

Reputation: 4944

Newer versions of GCC, clang and MSVC compilers implement the __has_include feature. Although it's a C++ 17 feature, I believe all three support it in plain C too.

But the traditional (and probably more portable) way is to check the existence of include files in a config script before the build process. Both autoconf and cmake have ways to achieve this.

#ifdef __has_include
    #if __has_include(<zconf.h>)
        #include <zconf.h>
    #else
        #include <unistd.h>
    #endif
#else
    #include <unistd.h>
#endif

Upvotes: 7

Related Questions