Adding quotes to argument in C++ preprocessor

Jonathan Zingman picture Jonathan Zingman · Jul 12, 2011 · Viewed 19.8k times · Source

I'd like to pass the name of an include file as a compiler argument so that I can modify a large number of configuration parameters. However, my C++ build is via a makefile like process that removes quotes from arguments passed to the compiler and pre-processor. I was hoping to do something equivalent to

#ifndef FILE_ARG
// defaults
#else
#include "FILE_ARG"
#endif

with my command line including -DFILE_ARG=foo.h. This of course doesn't work since the preprocessor doesn't translate FILE_ARG.

I've tried

#define QUOTE(x) #x
#include QUOTE(FILE_ARG)

which doesn't work for the same reason.

For scripting reasons, I'd rather do this on the command line than go in and edit an include line in the appropriate routine. Is there any way?

Answer

Karoly Horvath picture Karoly Horvath · Jul 13, 2011

For adding quotes you need this trick:

#define Q(x) #x
#define QUOTE(x) Q(x)

#ifdef FILE_ARG
#include QUOTE(FILE_ARG)
#endif