假设我有一堆定义一些变量的宏 - 它们需要在代码的不同部分中以两种方式定义(是的,这是一个糟糕的主意,但重构将需要很长的路要走。)
是否可以让以下代码段工作,即打印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;
}
答案 0 :(得分: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
在src文件中的用法:
int main()
{
#define ENABLE
#include "header"
std::cout << B << std::endl;
#undef ENABLE
#include "header"
std::cout << B << std::endl;
return 0;
}