How do I temporarily disable a macro expansion in C/C++?

后端 未结 5 1910
予麋鹿
予麋鹿 2020-12-08 00:54

For some reason I need to temporarily disable some macros in a header file and the #undef MACRONAME will make the code compile but it will undef the existing ma

5条回答
  •  半阙折子戏
    2020-12-08 01:03

    EDIT:

    You may think that it's that easy:

    #ifdef macro
    #define DISABLED_macro macro
    #undef macro
    #endif
    
    // do what you want with macro
    
    #ifdef DISABLED_macro
    #define macro DISABLED_macro
    #endif
    

    But it's not (like the following example demonstrates)!

    #include 
    #include 
    
    #include 
    
    #ifdef max
    #define DISABLED_max max
    #undef max
    #endif
    
    int main()
    {
        std::cout << std::numeric_limits::max() << std::endl;
    
    #ifdef DISABLED_max
    #define max DISABLED_max
    #endif
    
        std::cout << max(15,3) << std::endl;  // error C3861: "max": identifier not found
        return 0;
    }
    

    Using #undef on the macro and re-including the original header is also not likely to work, because of the header guards. So what's left is using the push_macro/pop_macro #pragma directives.

    #pragma push_macro("MACRO")
    #undef MACRO
    // do what you want
    #pragma pop_macro("MACR")
    

提交回复
热议问题