Adding quotes to argument in C++ preprocessor

こ雲淡風輕ζ 提交于 2019-11-29 16:21:01

问题


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?


回答1:


For adding quotes you need this trick:

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

#ifdef FILE_ARG
#include QUOTE(FILE_ARG)
#endif



回答2:


You can do

#ifdef FILE_ARG
#include FILE_ARG
#endif

On the command line

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

should do the trick.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/6671698/adding-quotes-to-argument-in-c-preprocessor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!