Expand define macro with include macro

2019-09-06 03:26发布

问题:

I'm trying to define a macro. The idea is that when it expands, it'll include a header. For example:

#define function() \
                   include <CustomHeader.h>

Thanks a lot.

回答1:

This can't be done.

The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, [...]

That particular quote is from a reasonably recent draft of the C++ standard, but with minor changes in wording, the same basic idea has been around nearly forever.



回答2:

As others have pointed out, you cannot produce a directive from a macro.

You can however produce the argument to a directive from a macro:

#define INCF(F) INCF_(F)
#define INCF_(F) #F
#define BAR foo.h

#include INCF(BAR)  // same as #include "foo.h"

But you can't get rid of that explicit #include, or insert it into the middle of a different line, or anything like that.