c++variablesc-preprocessorredefine

Avoid redefinition preprocessor variable


I have various preprocessor variables which have the same name in different libraries.

In order to avoid conflicts, what I am doing is (in the example there is only 1 conflicting variable and 1 header to include for simplicity):

#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 the conflicting variables, undefine them and restore them later?

Or is it possible to define a macro to perform these set of operations?


Solution

  • The C++ language does not provide an automated way to deal with preprocessor macro save and restore. Preprocessor macros (that are not defined from the compiler or the complier command line) work on a file global level, and there is no notion of restricting the scope of a macro to a particular header that is being #included.

    The way I would deal with such an issue is create a new header file that provides interface wrappers to the functionality I need from that particular library, but without any macro dependencies. Then implement the wrappers in a source file that only includes that troublesome header file.


    Your compiler may provide an extension to make the task a little less verbose, but not fully automated in the way that I understand you to mean.

    GCC and Microsoft compilers support push and pop macro pragmas.

    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 the value of the macro named as macro_name to the top of the stack for this macro.

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

    GCC documentation