How to redefine macroC # define C ++ using information from the macro itself?

Is it possible to override the C ++ #define macro using the information from the macro itself? I tried the code below, but because of how macros are evaluated, the result was not what I expected.

#include <iostream> #define FINAL_DEFINE "ABC" #define NEW_DEFINE FINAL_DEFINE "DEF" // Want ABCDEF #undef FINAL_DEFINE #define FINAL_DEFINE NEW_DEFINE // Want ABCDEF, but get empty? int main () { std::cout << FINAL_DEFINE << std::endl; // Want ABCDEF, but doesn't compile. } 
+5
source share
3 answers

Macros in macro objects never expand when defining a macro — only when using a macro. This means that the definition of NEW_DEFINE not "ABC" "DEF" , this is exactly what appears on the line #define: FINAL_DEFINE "DEF" .

Therefore, when you use FINAL_DEFINE , it expands to NEW_DEFINE , which then expands to FINAL_DEFINE "DEF" . At this point, it will not recursively extend FINAL_DEFINE (since this will lead to an infinite loop), so the extension no longer occurs.

+1
source

If your compiler supports the push_macro and pop_macro pragma directives, you can do this:

 #include <iostream> #define FINAL_DEFINE "ABC" #define NEW_DEFINE FINAL_DEFINE "DEF" int main () { std::cout << FINAL_DEFINE << std::endl; // Output ABC #pragma push_macro("FINAL_DEFINE") #define FINAL_DEFINE "XXX" std::cout << NEW_DEFINE << std::endl; // Output XXXDEF #pragma pop_macro("FINAL_DEFINE") } 
0
source

After preprocessing, all FINAL_DEFINE in the code will be replaced with the last thing that he defined, and then go to the compilation stage.

Thus, you cannot redefine the macro as you want.

Your compiler should warn you about this.

0
source

Source: https://habr.com/ru/post/1247492/


All Articles