xceph
xceph

Reputation: 1046

C Macro building with defines

I am having trouble getting this macro expanison right

#define foo Hello
#ifdef foo
#define wrapper(x) foo ## x
#else
#define wrapper(x) boo ## x
#endif

calling:

wrapper(_world)

I would like the result of

Hello_world

however, the macro is treating the "foo" define as a literal, and thus giving

foo_world

Can someone point out my mistake?

Thanks

Upvotes: 3

Views: 426

Answers (1)

styxyang
styxyang

Reputation: 96

I would recommend gnu-cpp-manual which clearly explains how macros are expanded.

Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they(macro arguments) are stringified or pasted with other tokens (by the macro function that is directly applied to).

For example:

If an argument is stringified or concatenated, the prescan does not occur.

#define AFTERX(x) X_ ## x
#define XAFTERX(x) AFTERX(x)
#define TABLESIZE 1024
#define BUFSIZE TABLESIZE

AFTERX(BUFSIZE) => X_BUFSIZE: since AFTERX is to concatenate argument with prefix, its argument is not expanded, remaining BUFSIZE.

XAFTERX(BUFSIZE) => X_1024: XAFTERX does not do concatenation directly, so BUFSIZE will be expanded first.

Generally, arguments are scanned twice to expand macro called in them.

--- edit ---

So the better practice is: (code from QEMU source)

#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

glue(x,y) will concatenate x and y with both already expanded.

Upvotes: 7

Related Questions