This question already has an answer here:
My mental model of how the preprocessor works is apparently incomplete, and this is driving me crazy.
I want to concatenate two tokens, but the second token should be expanded first.
#define ANSWER 42
#define FOO foo_ ## ANSWER
Here, FOO
expands to foo_ANSWER
, but I want it to be foo_42
. So I define a MERGE
macro in the hopes that this would somehow expand the arguments before concatenation:
#define MERGE(x, y) x ## y
#define BAR MERGE(bar_, ANSWER)
But BAR
still expands to bar_ANSWER
instead of bar_42
. So I define another macro HELPER
:
#define HELPER(x, y) MERGE(x, y)
#define BAZ HELPER(baz_, ANSWER)
And now BAZ
is successfully expanded to baz_42
. At the moment, this seems like magic to me.
Can anyone explain this behavior to me? How do the expansion rules work exactly?
Read the answer to your question here:
Token concatenation does not expand macros when performing concatenation [ref].
To get past this, you use a level of indirection, and get the preprocessor to expand the macros before the concatenation.