Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you include a header file that may or may not exist?

Let's assume I define BAR in foo.h. But foo.h might not exist. How do I include it, without the compiler complaining at me?

#include "foo.h"

#ifndef BAR
#define BAR 1
#endif

int main()
{
    return BAR;
}

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

like image 363
theanine Avatar asked Jul 19 '12 21:07

theanine


1 Answers

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

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

like image 106
Matthew Slattery Avatar answered Oct 03 '22 23:10

Matthew Slattery