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

发布于 2024-11-26 11:34:35 字数 335 浏览 4 评论 0原文

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

#define STR(x) #x

然后,STR(hi) 被替换为 "hi"

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

假设我有一个具有某些值的宏 CONSTANT,例如

#define CONSTANT 42

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

GNU's cpp allows you to turn macro parameters into strings like so

#define STR(x) #x

Then, STR(hi) is substituted with "hi"

But how do you turn a macro (not a macro parameter) into a string?

Say I have a macro CONSTANT with some value e.g.

#define CONSTANT 42

This doesn't work: STR(CONSTANT). This yields "CONSTANT" which is not what we want.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暖阳 2024-12-03 11:34:36

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

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

然后 STRING(CONSTANT) 根据需要生成 "42"

The trick is to define a new macro which calls STR.

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

Then STRING(CONSTANT) yields "42" as desired.

穿透光 2024-12-03 11:34:36

你需要双重间接魔法:

#define QUOTE(x) #x
#define STR(x) QUOTE(x)

#define CONSTANT 42

const char * str = STR(CONSTANT);

You need double indirection magic:

#define QUOTE(x) #x
#define STR(x) QUOTE(x)

#define CONSTANT 42

const char * str = STR(CONSTANT);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文