代码之家  ›  专栏  ›  技术社区  ›  Carbon

可以在一大块C++宏之间切换吗?

  •  2
  • Carbon  · 技术社区  · 9 年前

    假设我有一堆宏定义一些变量——它们需要在代码的不同部分以两种方式定义(是的,这是个坏主意,但重构需要很长的时间)。

    有没有可能让下面的代码片段工作,也就是说,先打印4,然后打印1?

    #include <iostream>
    #define ENABLE
    #ifdef ENABLE
    #define B 4
    #define C 5
    //imagine a bunch more here
    #else
    #define B 1
    #define C 2
    //imagine a bunch more here
    #endif
    
    int main()
    {
        std::cout << B << std::endl;
    #pragma push_macro("ENABLE")
    #undef ENABLE
        std::cout << B << std::endl;
    #pragma pop_macro("ENABLE")
    
        return 0;
    }
    

    #include <iostream>
    #define B 4
    
    int main()
    {
    #pragma push_macro("B")
    #undef B
    #define B 1
        std::cout << B << std::endl;
    #pragma pop_macro("B")
        std::cout << B << std::endl;
        return 0;
    }
    
    1 回复  |  直到 9 年前
        1
  •  10
  •   Robᵩ    9 年前

    你也许可以通过反复做这件事 #include 读取头文件:

    标题:

    // Note: no inclusion guards!
    #undef B
    #undef C
    #ifdef ENABLE
    #define B 4
    #define C 5
    //imagine a bunch more here
    #else
    #define B 1
    #define C 2
    //imagine a bunch more here
    #endif
    

    int main()
    {
    #define ENABLE
    #include "header"
        std::cout << B << std::endl;
    #undef ENABLE
    #include "header"
        std::cout << B << std::endl;
        return 0;
    }