1
votes

I want to use a macro defined in different header files with the same name and different implementations. I have two header files h1.h and h2.h. In the first header file I defined:

#define PRINT  printf(" hi , macro 1\n"); 

and in the second header file

#define PRINT  printf(" hi , macro 2\n");

in main() when I try to use PRINT it is printed depending on the order of inclusion. I found some similar problems and they used a wrapper, by including the first header file then defining an inline method:

inline void print1() {
      PRINT();
}

and then undefining PRINT and including the second header file. In main() when I call print1() and PRINT I got the output from them both. My missing point is how after we have undefined the PRINT from the first header file we are still able to have it - in other words what happens when we call it inside the inline function? Did the compiler copy the value of PRINT and assign it to the function and save the function in some way?

2
Surprise surprise, you're using a preprocessor MACRO... :-) - Sourav Ghosh

2 Answers

3
votes

If I understand correctly, something like this is happening:

#include "h1.h" // defines PRINT: printf(" hi , macro 1\n"); 

inline void print1(){
    PRINT();
}

#undef PRINT

#include "h2.h" // defines PRINT: printf(" hi , macro 2\n");

Nothing weird happens though. The pre-processor substitues PRINT inside the inline function before it is un-defined. So in the resulting code (you can see this when you compile with the -E flag for GCC), it becomes this:

// contents of h1.h...

inline void print1(){
    printf(" hi , macro 1\n");
}

// contents of h2.h...

#defined macros are only kept for the duration of the pre-processing, and are substituted as the pre-processor goes along. Similar to variables in normal programming, if you re-assign it the pre-processor will just use the new value for following occurrences.

1
votes

It works because during compilation the pre-processor reaches the PRINT() call in print1, evaluates the macro, and replace it with its current value. Then, if I understand correctly, later (in the next lines) you redefine or undefine PRINT (be it by including another header), then any further reference to it will make the pre-processor replace it with its current value again (which is now different), therefore you get 2 distinct behaviours calling the "same" macro.