-D option is expanded incorrectly from g++ command line

倖福魔咒の 提交于 2019-12-13 14:39:23

问题


In C++ CodeBlocks project I added the following definitions to the project settings, compiler settings, #define:

_DEBUG
DATA_DIR=\"/media/Shared/SiX/Data\"

This produces the following g++ command line:

g++ -Wall  -g -fPIC -save-temps -D_DEBUG -DDATA_DIR=\"/media/Shared/SiX/Data\"    -I../Includes  -c /media/Shared/SiX/SiXConfiguration/PathManager.cpp -o obj/Debug/PathManager.o

This code does not compile:

char* commonDataDir;
#ifdef DATA_DIR
commonDataDir = DATA_DIR;
#endif

Looking at preprocessor output file, I see that source code line is expanded in this way:

commonDataDir = /media/Shared/SiX/Data;

I expect:

commonDataDir = "/media/Shared/SiX/Data";

The same code is compiled correctly from Eclipse CDT:

g++ -D_DEBUG -DDATA_DIR=\"/media/Shared/SiX/Data\" -I"/media/Shared/SiX (copy)/Includes" -O3 -Wall -c -fmessage-length=0 -fPIC -ggdb -MMD -MP -MF"PathManager.d" -MT"PathManager.d" -o"PathManager.o" "../PathManager.cpp"

So, the same command line parameter is handled differently by g++ proprocessor. How can I fix this?


回答1:


Putting quotes on macros is tricky and not a good idea.
Try and use the pre-processor to add the required quotes.

#define DO_QUOTE(X)       #X
#define QUOTE(X)          DO_QUOTE(X)

#ifndef DATA_DIR
#define DATA_DIR       /tmp
#endif

char commonDataDir[] = QUOTE(DATA_DIR);



回答2:


In Code::Blocks Project build options->Compiler settings->#defines

DATA_DIR=\\"/media/Shared/SiX/Data\\"

(This not just a guess but what I do regularly)




回答3:


You need to enclose the whole string in "

-DDATA_DIR="\"/media/Shared/SiX/Data\""
           ^                          ^



回答4:


This seems to fix it.

g++ -DDATA_DIR='"/media/Shared/SiX/Data"' ...



回答5:


I just used a line similar to -DDATA_DIR=\"/media/Shared/SiX/Data\" inside a make file on a current project and it worked just fine. (Single back-slash and double-quote.)

Environment:

> uname -a
Linux ... 3.16.0-5-amd64 #1 SMP Debian 3.16.51-3+deb8u1 (2018-01-08) x86_64 GNU/Linux
> make -v
GNU Make 4.0
Built for x86_64-pc-linux-gnu
> g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.9/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ...
Thread model: posix
gcc version 4.9.2 (Debian 4.9.2-10+deb8u1)


来源:https://stackoverflow.com/questions/3959398/d-option-is-expanded-incorrectly-from-g-command-line

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