1

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.

onqtam
  • 4,356
  • 2
  • 28
  • 50

2 Answers2

3

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).
H Walters
  • 2,634
  • 1
  • 11
  • 13
  • such a shame that I can't attach defines on header files and only on source files (but it makes sense though...) - otherwise I could simulate this with my build system... – onqtam Aug 23 '17 at 15:52
  • Your build system is open ended... you could simply use another tool to generate the include files. – H Walters Aug 23 '17 at 16:19
1

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

Look at the second answer of this question:

C Macro - Dynamic #include

drone6502
  • 433
  • 2
  • 7