How do GCC process macros when one reference the other

Viewed 13
//foo.h

#define X TEST-9

#define TEST 10

//foo.c
#include<stdio.h>
#include"foo.h"

int main(void)
{
  int a = X;
  printf("%d\n", a);
}

when I run :

gcc -o foo foo.c -Wall -Wextra

there is no outout,then run:

./foo

result is: 1

my queston is:

X references TEST,but TEST is defined after X,why can X expansion correctly

1 Answers

X references TEST,but TEST is defined after X,why can X expansion correctly

Expansion happens upon use. When X is used at line int a = X, #define TEST is visible.

It's string replacement. X is expanded to the string TEST-9 then that string is rescanned for further replacements, TEST is found, and then TEST is replaced by 10, resulting in the string 10-9.

Related