Home > Back-end >  Can I nest `#include` in a macro?
Can I nest `#include` in a macro?

Time:03-23

I'm building a back end interface that can be expanded by third parties, and I want to make it as easy as possible to add a new back end module.

To do so, I'd like to automate the inclusion of unknown header files by just requiring to add an entry to an X macro:

store.h:

#define BACKEND_TBL \
ENTRY(HTABLE, "store_htable.h", htstore, htiter) \
ENTRY(MDB, "store_mdb.h", mdbstore, mdbiter)
/* Add more here */

typedef enum store_type {
#define ENTRY(a, b, c, d) STORE_##a,
BACKEND_TBL
#undef ENTRY
} StoreType;

store.c:

#include "store.h"

#define ENTRY(a, b, c, d) #include b
BACKEND_TBL
#undef ENTRY

I get an error: # is not followed by a macro parameter.

I tried to escape the # before #include since that is a stringizing token, but still won't work.

Is this even possible in C?

CodePudding user response:

No, this is not possible. While you can, say, #define MYHDR <header.h> and then #include MYHDR, macro substitution is performed after lexing preprocessor commands. If you did #define INCLUDE_FOO #include <foo.h> (and somehow got that through the preprocessor rather than having it treated as stringizing), then adding INCLUDE_FOO would just result in the text #include <foo.h> in the post-preprocessor source, which would lead to syntax errors when compiling.

CodePudding user response:

Alternatively, what you could do is this, Use a macro to control the definiation block,

#ifdef USE_HTABLE
    #include <htabl.h>
#endif
#ifdef INCLUDE_MDB
    #include <MDB.h>
#endif

And when you need just do,

#define INCLUDE_MDB

  • Related