How to include a header file that may or may not exist?

Suppose I define a BAR in foo.h. But foo.h may not exist. How to enable it without a compiler complaining about me?

#include "foo.h" #ifndef BAR #define BAR 1 #endif int main() { return BAR; } 

Therefore, if the BAR was defined as 2 in foo.h, then the program will return 2 if foo.h exists, and 1 if foo.h does not exist.

+6
source share
2 answers

In general, you need to do something external for this - for example, by doing something like playing around a search path (as suggested in the comments) and providing empty foo.h as a backup or wrapping #include inside a #ifdef HAS_FOO_H ... #endif and setting HAS_FOO_H using the compiler ( -DHAS_FOO_H for gcc / clang, etc.).

If you know that you are using a specific compiler, and portability is not a problem, note that some compilers support, including a file, which may or may not exist, as an extension. For example, see clang __has_include .

+8
source

Use a tool like the GNU Autoconf for which it is intended. (In windows you can use CMake ).

So in your configure.ac you will have a line like:

 AC_CHECK_HEADERS([foo.h]) 

Which, after running configure , would define HAVE_FOO_H , which you can test as follows:

 #ifdef HAVE_FOO_H #include "foo.h" #else #define BAR 1 #endif 

If you intend to go down the autotools route (these are autoconf and automake, because they work well together), I suggest you start with this great tutorial .

+6
source

Source: https://habr.com/ru/post/920919/


All Articles