简体   繁体   中英

Create object-like macro from concatenation of token and macro

I want create an object-like macro from the concatenation of token and macro. I have this code:

#define alfa vita
/* Code below is broken. */
#define gamma delta##alfa
gamma

The gamma is replaced with deltaalfa . I want it replaced with deltavita . How can I do this?

I don't want the gamma to be a function-like macro.


What are the applications of the ## preprocessor operator and gotchas to consider?
This question is very broad. It isn't focused on my problem and the first answer doesn't address it either.

You must perform a double macro expansion like so:

#define alfa vita

#define concat2(a,b) a ## b
#define concat(a,b) concat2(a,b)
#define gamma concat(delta, alfa)

gamma

The operands of the stringification ( # ) and token pasting ( ## ) operators are not first expanded. As a special case, expansion of a function-style macro proceeds by first expanding the arguments except where they are operands of the # or ## operator , then substituting them into the macro body, then rescanning for substitutions.

The double-expansion approach above works because the arguments of the concat() macro are not operands of ## (or # ). They are therefore expanded before being substituted into that macro's body to yield

concat2(delta, vita)

Upon rescanning, that is expanded further to

delta ## vita

(regardless of any macro definition for the symbol vita ), which is then pasted together into a single token to yield the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM