40

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jonathan Zingman
  • 401
  • 1
  • 4
  • 3

4 Answers4

59

For adding quotes you need this trick:

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

#ifdef FILE_ARG
#include QUOTE(FILE_ARG)
#endif
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Since FILE_ARG doesn't have quotes, the first doesn't work because include expects quotes or <>. – Jonathan Zingman Jul 12 '11 at 22:08
  • When you use a macro as an argument for a macro it's only substituted when it is not used with # or ##, so you need an additional processing level. http://stackoverflow.com/questions/3419332/c-preprocessor-stringify-the-result-of-a-macro – Karoly Horvath Jul 12 '11 at 23:38
  • I use this trick to add quotation marks when building libtiff with JPEG 8/12 bit dual mode turned on. – user5280911 Jun 21 '18 at 15:21
9

You can do

#ifdef FILE_ARG
#include FILE_ARG
#endif

On the command line

$ gcc -DFILE_ARG="\"foo.h\"" ...

should do the trick.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jobless
  • 145
  • 1
  • 1
  • 4
2

You can also try the -include switch.

gcc manual:

-include file

Process file as if #include "file" appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor's working directory instead of the directory containing the main source file. If not found there, it is searched for in the remainder of the #include "..." search chain as normal. If multiple -include options are given, the files are included in the order they appear on the command line.*

Sophy Pal
  • 435
  • 2
  • 7
0

Works for me. Maybe you forgot to quote correctly in your Makefile?

$ cat example.c
#include FILE_ARG

$ cat test.h
#define SOMETHING

$ gcc -Wall -Wextra -W -DFILE_ARG=\"test.h\" -c example.c
$ 

EDIT: The reason you might not be able to get quoting to work is because the preprocessor works in phases. Additionally I used "gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2", results may vary between compilers.

user786653
  • 29,780
  • 4
  • 43
  • 53