开发者

Adding quotes to argument in C++ preprocessor

开发者 https://www.devze.com 2023-03-19 15:20 出处:网络
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 q

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?


For adding quotes you need this trick:

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

#ifdef FILE_ARG
#include QUOTE(FILE_ARG)
#endif


You can do

#ifdef FILE_ARG
#include FILE_ARG
#endif

On the command line

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

should do the trick.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号