Search code examples
buildheader-filesoptional-arguments

How to compile if a header does not exist?


#include "MyHeader.h"

I would like MyHeader.h to be optional, i.e. to build even if it is not available.
Can I do it with the preprocessor, without involving the build system?


Solution

  • No, not really, not with the standard preprocessor anyway. The #include directive is a fairly simple one which just basically drags in the object as if it was part of the translation unit. You could wrap the include in a macro check:

    #ifdef USE_MY_HEADER
        #include "MyHeader.h"
    #endif
    

    but that would still require input from the build system somehow.

    There are no facilities in the standard preprocessor to bring in a file only if it exists but there are several avenues you may want to examine, such as:

    1. Just ensure there always is a file, even an empty one. That way, you can include it easily, and the user can modify it to add whatever they need. They just can't delete it.

    2. Have your build system check for the existence of the file before compiling anything that uses it and, if it does not exist, create an empty one.

    3. Think about whether this is needed at compile time. That should only be necessary if it needs to affect the actual compilation itself. If it's simply to affect the way the program behaves at run time, you could just as easily have a configuration file that's read by your program and uses the information to change behaviour. That way, you can detect a non-existent file and just ignore it.