gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:31 25 4
gpt4 key购买 nike

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

为了避免冲突,我正在做的是(在示例中,为简单起见,只有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com