引用宏的展开值
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?
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?