是否可以在大块C++宏之间切换?

Car*_*bon 2 c++ macros c-preprocessor

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

是否有可能让下面的代码段工作,即打印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;
}
Run Code Online (Sandbox Code Playgroud)

通过具体定义B当然可以达到相同的效果,但如果我有一大块宏,那么这不是100%实用:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 10

您可以通过重复#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
Run Code Online (Sandbox Code Playgroud)

在src文件中的用法:

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