-
12-12-2019 - |
题
这让我坚果。我在命令行上有一个宏,使用-D
选项
-DFOO="foobarbaz"
.
然后我想做这样的事情
string s = "FOO" ;
.
获取
string s = "foobarbaz" ;
.
因为显然,即使我尝试使用\
逃脱它们,也会消除命令行的引号。我尝试了一切,我可以用纵曲和额外的宏来思考,它只是不起作用。要么我收到关于错误处理器的错误处理程序的错误,或者我最终会使用
string s = foobarbaz ;
.
显然不会编译。
解决方案
在命令行上使用它:
-DFOO="\"hello world\""
.
例如test.cpp是:
#include <cstdio>
#include <string>
#include <iostream>
std::string test = FOO;
int main()
{
std::cout << test << std::endl;
return 0;
}
.
编译和运行给出:
$ g++ -DFOO="\"hello world\"" test.cpp
$ ./a.out
hello world
.
编辑这是您将如何从makefile执行以下操作:
DEFS=-DFOO="\"hello world\""
test: test.cpp
$(CXX) $(DEFS) -o test test.cpp
. 其他提示
C和C ++预处理器被调整为C和C ++,它们是不是原始的,byte-byte预处理。它们识别字符串(如世代odicetagcode),并且不会匹配和展开它们。如果要展开宏,则必须在字符串之外执行。例如,
#define foo "bar"
#include <string>
int main () {
std::string s = "Hello " foo "! How's it going?";
}
.
上面的字符串将扩展到
Hello bar! How's it going?
. 不隶属于 StackOverflow