c++ - 避免重新定义预处理器变量

标签 c++ variables c-preprocessor redefine

我有各种预处理器变量,它们在不同的库中具有相同的名称。

为了避免冲突,我正在做的是(在示例中,为简单起见,只有 1 个冲突变量和 1 个 header 要包含):

#ifdef VAR
#define TEMPVAR VAR
#undef VAR
#endif   

#include "conflictingheader.hh" 

#ifdef VAR
#undef VAR
#endif

#ifdef TEMPVAR
#define VAR TEMPVAR
#undef TEMPVAR
#endif

是否有一种自动存储所有冲突变量、取消定义并在以后恢复它们的方法?

或者是否可以定义一个宏来执行这些操作集?

最佳答案

C++ 语言不提供自动处理预处理器宏保存和恢复的方法。预处理器宏(不是从编译器或编译器命令行定义的)在文件全局级别上工作,并且没有将宏的范围限制到正在被 #include 的特定 header 的概念>d.

我处理此类问题的方法是创建一个新的头文件,为我需要的特定库的功能提供接口(interface)包装器,但没有任何宏依赖性。然后在仅包含该麻烦的头文件的源文件中实现包装器。


您的编译器可能会提供一个扩展来使任务不那么冗长,但不会按照我理解您的意思完全自动化。

GCC 和 Microsoft 编译器支持 push 和 pop 宏编译指示。

For compatibility with Microsoft Windows compilers, GCC supports #pragma push_macro("macro_name") and #pragma pop_macro("macro_name").

#pragma push_macro("macro_name")
This pragma saves the value of the macro named as macro_name to the top of the stack for this macro.

#pragma pop_macro("macro_name")
This pragma sets the value of the macro named as macro_name to the value on top of the stack for this macro. If the stack for macro_name is empty, the value of the macro remains unchanged.

GCC documentation

关于c++ - 避免重新定义预处理器变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266276/

相关文章:

java - 以最佳方式计算 x 的 x 次方

c++ - 是否可以使用友元函数将类类型转换为基本类型?

php变量改变结果

arrays - 根据输入 swift 组装一个变量

python - 在不使用全局的情况下调用不同函数中的变量

c - 嵌套 C 宏、CRC 计算、Eclipse Java 崩溃

c++ - 基本 3D OpenGL 碰撞检测 C++

c++ - 组合多个变量以作为 udp 数据包发送

c++ - 获取 if 语句以检查定义的宏

c++ - 标记粘贴运算符 (##) 正在占用我的 C++ 宏中的空格