如何使用cpp将宏转换为字符串?

How do I turn a macro into a string using cpp?

本文关键字:字符串 转换 何使用 cpp      更新时间:2023-10-16

GNU的cpp允许您将宏参数转换为如下字符串

#define STR(x) #x

STR(hi)代入"hi"

但是如何将宏(不是宏参数)转换为字符串呢?

假设我有一个宏常量与一些值,例如

#define CONSTANT 42

这不起作用:STR(CONSTANT)。这产生了"CONSTANT",这不是我们想要的。

诀窍是定义一个新的宏来调用STR

#define STR(str) #str
#define STRING(str) STR(str)

STRING(CONSTANT)生成"42"

你需要双重间接魔法:

#define QUOTE(x) #x
#define STR(x) QUOTE(x)
#define CONSTANT 42
const char * str = STR(CONSTANT);