引用宏的展开值

Quoting the expanded value of a macro

本文关键字:引用      更新时间:2023-10-16

这让我抓狂。我在命令行上定义了一个带有-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++,它们是而不是原始的逐字节预处理器。它们可以识别字符串(如"foo"),并且不会在字符串中匹配和扩展。如果要展开宏,必须在字符串之外进行。例如,

#define foo "bar"
#include <string>
int main () {
    std::string s = "Hello " foo "! How's it going?";
}

以上字符串将扩展到

Hello bar! How's it going?