简体   繁体   中英

how to append to __FILE__ at preprocessor time and include the result

I want to include component.h.gen from component.h .

I've already seen that I can use __FILE__ with #include and that results in recursive inclusion if there is no header guard.

Is there a way to append a C string literal and include the result? This is what I've tried so far:

#define CAT_IMPL(s1, s2) s1##s2
#define CAT(s1, s2) CAT_IMPL(s1, s2)
#define DO_IT CAT(__FILE__, ".gen")

#include DO_IT

But this results in the same recursion with the file including itself - the ".gen" part is not used - and I get this warning with MSVC:

warning C4067: unexpected tokens following preprocessor directive - expected a newline

Is there a solution that would work with gcc/clang/msvc?

Note that I'm planning on using this in hundreds if not thousands of files and I would like to simplify my life by just copy-pasting the same code - that's why I'm trying to get this to work.

Unfortunately, this is not possible:

  • __FILE__ expands to a string; you cannot unstringify a string. So the technique of just adding the "rest" of the string, then stringifying the result, isn't available.
  • Pasting two string tokens does not create a valid token. So pasting isn't available.
  • String literal concatenation doesn't exist for the preprocessor (preprocessor is translation phase 4; string literal concatenation is phase 6).

Kind of obscure, but seems to be possible with gcc.

Look at the second answer of this question:

C Macro - Dynamic #include

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM