Search code examples
c++includeheader-filespreprocessorcompiler-flags

How do I automatically select an include.h file based on compiler directive -D?


I would like to have a general include.h header file in my program that will list all possible include files to be used when selected using a -D ITEM=ITEM1 compiler flag. If I want to build this library for example for ITEM1, then -D ITEM=ITEM1 for item2, it will be -D ITEM=ITEM2.

header.h file:

#ifdef ITEM1
#include item1.h
#endif
#ifdef ITEM2
#include item2.h
#endif

the header files item1.h and item2.h will be a symbolic link from another directory outside of the working directory.

When I do this scheme, I get scope errors on the defines inside each of item1.h or item2.h


Solution

  • You can use -D ITEM1 or -D ITEM2 for your posted code to work. If you want to base your logic of -D ITEM=..., you'll need to use -D ITEM=1 or -D ITEM=2 and change your code to:

    #ifdef ITEM
    
    #if ITEM == 1
    #include item1.h
    #elif ITEM == 2
    #include item2.h
    #else
    // Unknown value of ITEM. Figure out what do for this case.
    #endif
    
    #else
    // ITEM is not defined. Figure out what do for this case.
    #endif