11

I would like to use an #include directive with a file name that is passed as an externally defined macro.

E.g.

#include #FILE".h"

where FILE would be defined as the string MyFile (without quotes), resulting in

#include "MyFile.h"

The stringizing operator # cannot be used here as the symbol FILE is not a macro argument. I have tried other approaches, to no avail.

Do you see a solution ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    gcc provides some functionality to *externally* include files http://stackoverflow.com/questions/3387453/include-header-files-using-command-line-option. This may helps you. – Jean-Baptiste Yunès Oct 27 '15 at 08:11
  • Interesting. I am using both gcc and MSVC, and my #include directive may not be in the first position. –  Oct 27 '15 at 08:15
  • 2
    It won't be possible, since adjacent string literal concatenation is not done until after the preprocessor stage, so e.g. `"MyFile"".h"` will not be a valid include name. Can't you simply define `FILE` as the actual header name to be included, e.g. `-DFILE="MyFile.h"`? – Some programmer dude Oct 27 '15 at 08:18
  • See this one (solution 2) http://stackoverflow.com/questions/30465646/expand-define-macro-with-include-macro – Jean-Baptiste Yunès Oct 27 '15 at 08:19
  • @JoachimPileborg: I'll do it as a last resort. –  Oct 27 '15 at 08:21

1 Answers1

15

String literal concatenation happens two translation phases after #include-directives are resolved; your approach cannot work. Instead, try something along the lines of

#define STRINGIZE_(a) #a
#define STRINGIZE(a) STRINGIZE_(a)

#define MYFILE stdio
#include STRINGIZE(MYFILE.h)

int main() {
    printf("asdf");
}

Demo.

Columbo
  • 60,038
  • 8
  • 155
  • 203