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

Is it possible to flip between a large block of C++ macros?

本文关键字:C++ 之间 是否      更新时间:2023-10-16

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

是否有可能让下面的代码片段工作,即打印出 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;
}

通过专门定义 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;
}
您可以通过

重复#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

src 文件中的用法:

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