Avoid overriding the preprocessor variable

I have different preprocessor variables that have the same name in different libraries.

To avoid conflicts, I do this (in the example, for simplicity, there is only one conflicting variable and 1 header):

#ifdef VAR #define TEMPVAR VAR #undef VAR #endif #include "conflictingheader.hh" #ifdef VAR #undef VAR #endif #ifdef TEMPVAR #define VAR TEMPVAR #undef TEMPVAR #endif 

Is there an automatic way to store all conflicting variables, undefine them and restore them later?

Or can you define a macro to perform these operations?

+5
source share
2 answers

C ++ does not provide an automated way to handle saving and restoring preprocessor macros. Preprocessor macros (which are not defined from the compiler or the compiler command line) work at the global file level, and there is no concept of restricting the macro area to a specific header, which has the value #include d.

The way I came across such a problem is to create a new header file that provides front-end shells for the function I need from this particular library, but without any macro dependencies. Then implement wrappers in the source file, which includes only this nasty header file.


Your compiler can provide an extension to make the task a little less detailed, but not fully automated as I understand what you mean.

GCC and Microsoft compilers support push pop macros.

For compatibility with Microsoft Windows compilers, GCC supports #pragma push_macro("macro_name") and #pragma pop_macro("macro_name") .

#pragma push_macro("macro_name")
This pragma saves a macro value named macro_name at the top of the stack for this macro.

#pragma pop_macro("macro_name")
This pragma sets a macro value named macro_name to a value on top of the stack for this macro. If the stack for macro_name empty, the macro value remains unchanged.

GCC Documentation

+7
source

There is no standard way to do this. @jxh has a great non-standard way. The reason it does not work is because macros are not evaluated at all until they are extended, they will not be evaluated when used in another macro definition.

 #define MY_MACRO VAR #define MY_STR_MACRO2(M) # M #define MY_STR_MACRO(M) "MY_MACRO = " MY_STR_MACRO2(M) "\n" printf(MY_STR_MACRO(MY_MACRO)); //writes "VAR" #define VAR 4 printf(MY_STR_MACRO(MY_MACRO)); //writes "4" #undef VAR printf(MY_STR_MACRO(MY_MACRO)); //writes "VAR" again 

In each line of printf he looks at MY_MACRO and sees that it is a "VAR", and then looks to see if there is a VAR for anything. Sometimes it is, sometimes it is not.

So, when you try this:

 #define TEMPVAR VAR 

The only thing that is recorded in TEMPVAR is "VAR". Everything that can evaluate VAR is not considered at this point and will not be until TEMPVAR is evaluated.

0
source

All Articles