Jonathan Zingman
Jonathan Zingman

Reputation: 431

Adding quotes to argument in C++ preprocessor

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?

Upvotes: 43

Views: 27731

Answers (4)

jobless
jobless

Reputation: 145

You can do

#ifdef FILE_ARG
#include FILE_ARG
#endif

On the command line

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

should do the trick.

Upvotes: 9

user786653
user786653

Reputation: 30480

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.

Upvotes: 0

Sophy Pal
Sophy Pal

Reputation: 435

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.*

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96306

For adding quotes you need this trick:

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

#ifdef FILE_ARG
#include QUOTE(FILE_ARG)
#endif

Upvotes: 64

Related Questions