如何使用 cpp 将宏转换为字符串?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
诀窍是定义一个调用
STR
的新宏。然后
STRING(CONSTANT)
根据需要生成"42"
。The trick is to define a new macro which calls
STR
.Then
STRING(CONSTANT)
yields"42"
as desired.你需要双重间接魔法:
You need double indirection magic: