Macro re-entrancy problem

Macro re-entrancy problem

Post by Lauri Alan » Sat, 05 Feb 2011 22:14:44

I encountered a somewhat *** macro problem:

#define FOO(x) BAR_##x
#define BAR_z 42
#define BAR_q FOO(z)
#define BAZ(x) BAR_##x

int main(void) {
int a = FOO(z);
int b = BAZ(q);
int c = FOO(q); // line 9
return 0;

$ gcc -o t t.c
t.c: In function 'main':
t.c:9: error: 'z' undeclared (first use in this function)
t.c:9: error: (Each undeclared identifier is reported only once
t.c:9: error: for each function it appears in.)

The preprocessor output from gcc -E is:

int main(void) {
int a = 42;
int b = 42;
int c = FOO(z);
return 0;

So it seems that a macro invocation cannot trigger the invocation of
the same macro again, even indirectly, even if the expansion would
ultimately terminate. Is this standard behavior, or a bug in gcc?



Macro re-entrancy problem

Post by Ben Bacari » Sat, 05 Feb 2011 23:05:46

Lauri Alanko < XXXX@XXXXX.COM > writes:

It's standard. For chapter and verse, see paragraph 2 of C99.

The restriction applies to the macro text being expanded. When the
macro expansion involves further "new" text from the source, the
expansion will be made:

#define M0(x) R1 M1
#define M1(x) R2 M0


expands to R1 R2 R1 R2 M0.