C宏建筑与定义

xce*_*eph 3 c macros

我无法正确使用这个宏扩展

#define foo Hello
#ifdef foo
#define wrapper(x) foo ## x
#else
#define wrapper(x) boo ## x
#endif
Run Code Online (Sandbox Code Playgroud)

电话:

wrapper(_world)
Run Code Online (Sandbox Code Playgroud)

我想结果

Hello_world
Run Code Online (Sandbox Code Playgroud)

然而,宏正在将"foo"定义为文字,从而给予

foo_world
Run Code Online (Sandbox Code Playgroud)

有人可以指出我的错误吗?

谢谢

sty*_*ang 7

我会推荐gnu-cpp-manual,它清楚地解释了如何扩展宏.

宏参数在被替换为宏体之前是完全宏扩展的,除非它们(宏参数)被字符串化或粘贴到其他标记(通过直接应用的宏函数).

例如:

如果参数被字符串化或连接,则不会发生预扫描.

#define AFTERX(x) X_ ## x
#define XAFTERX(x) AFTERX(x)
#define TABLESIZE 1024
#define BUFSIZE TABLESIZE
Run Code Online (Sandbox Code Playgroud)

AFTERX(BUFSIZE) => X_BUFSIZE:既然AFTERX是用前缀连接参数,它的参数不会扩展,剩下BUFSIZE.

XAFTERX(BUFSIZE) => X_1024:XAFTERX不直接连接,因此BUFSIZE将首先扩展.

通常,参数被扫描两次以扩展在其中调用的宏.

---编辑---

所以更好的做法是:(来自QEMU源代码)

#ifndef glue
#define xglue(x, y) x ## y
#define glue(x, y) xglue(x, y)
#define stringify(s) tostring(s)
#define tostring(s) #s
#endif
Run Code Online (Sandbox Code Playgroud)

glue(x,y)将连接x并且y已经扩展.