C-Pre-Processor macros order -


i followed tutorial involved doing cpp macros implement debug system in program. 1 great behavior of macros being recursive, making possible put macro inside macro below:

#define macro1 "world" #define macro2 printf("hello %s\n",macro1); #include<stdio.h> #include<stdlib.h>  int main(int argc, char *argv[]){     macro2     return 0; } 

output: hello world

the below seems work:

#define macro2 printf("hello %s\n",macro1); #define macro1 "world" #include<stdio.h> #include<stdlib.h>  int main(int argc, char *argv[]){     macro2     return 0; } 

so understand, cpp first reads #define x make list of declared macros, substitute macros inside other macros, avoiding "chicken , egg" issue on pre-processing?

i think makes sense, considering pre-processing one-time process (during compilation), not happening in real time. shouldn't matter in code macro defined, if defined @ all.

having 3000 lines code , in last line defining macro used in code valid then?

thank in advance!

what happens recursive substitution happens when macro used, not when it's defined.

so at

#define macro2 printf("hello %s\n",macro1); 

the preprocessor memorizes macro2 expands 7 tokens printf, (, "hello %s\n", ,, macro1, ), , ;. @ point doesn't care if of tokens macros.

at point in main do

macro2 

the preprocessor expands macro 7 tokens, , checks see whether token stream contains more macros can expanded again. notices macro1 , substitutes token "world". @ point checks again, there no more macros expansion.

you'll still run problems if try use macro before it's been #defined.


Comments