Is there a preprocessor that can check if a header exists before trying to #include it?

Not as far as I know. There might be some compiler extension that does this, but nothing standard.

This kind of thing is generally handled by the build system and/or compilation flags. Technically speaking, there could be a way to obtain information from the compiler whether a header file exists or not, but that would be crude at best and not very useful. Generally, you use a build system (such as cmake, autoconf, Boost.Build, etc.) to do things like checking if a header file exists, finding the path to a header file that you're not sure where it could be, finding alternative paths / libraries to use, and doing things like disabling the compilations of some source files under some conditions, and so on.. This is what a build system (or build configuration system) is useful for, so, that's where you should be doing that kind of thing. Once you determine what optional headers exist, you would typically set certain defines (#define) that you can test in your code, for example:

#if defined(HAVE_FOUND_OPENCV_HDR)

#include <cv.h>
#include <cvaux.h>

#elif defined(HAVE_FOUND_FREEIMAGE_HDR)

#include <FreeImage.h>

#else

#error "No appropriate image library installed on the system! Options are OpenCV or FreeImage."

#endif

Another mechanism for this kind of thing is to assess the nature of the platform you are compiling for by using pre-processor definitions that are defined by the compiler. These defines generally can be used to infer which compiler is being used, what OS it is compiling for, and on what architecture (type of processor) it is compiling for. These can be used to "select" the right system-specific headers to include.

Would you might telling us exactly in what context you need this "try-include" mechanism? It will help us to help you find an appropriate solution.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.