定义一个宏,然后取消定义之前未定义的宏
Define a macro then undefine it if it was previously undefined
我包括头文件,需要某些专业处理器#define
存在,但我不希望这污染我的代码的其余部分,例如:
// FOO may or may not already be defined here
#define FOO
#include "Bar.h"
#undef FOO
// FOO should be defined or not, as per the starting state
我在想:
#ifdef FOO
#define FOO_DEFINED
#endif
#define FOO
#include "Bar.h"
#ifndef FOO_DEFINED
#undef FOO
#else
#undef FOO_DEFINED
#endif
问题:
将上述工作,即恢复所有宏定义(或缺乏)到他们之前的状态?
有没有更简单的解决方案?
如果FOO已经被定义当我
#define
它重要吗?我应该添加另一个#ifndef
来防止这种情况吗?
在您的示例中,Bar.h似乎只关心FOO是否定义,而不关心绑定到它的实际表达式。此外,如果其他人(我假设您的代码示例本身在头文件中)定义了FOO并关心绑定到它的表达式,那么您不希望犯用空表达式重新定义FOO的错误。如果是这样,您可能需要简化:
#ifndef FOO
#define FOO
#define UNDEF_FOO
#endif
#include "Bar.h"
#ifdef UNDEF_FOO
#undef FOO
#endif
- 我有#pragma push_macro/pop_macro("macro_name")在脑海中,但它可能只在gcc和MS vc++中工作
- 是的,这很重要,如果用不同的值再次定义它,你会得到一个警告。正如你所说,你可以用#ifndef屏蔽它。
相关文章:
- C++宏定义和取消定义
- C++错误:在类中取消对main的定义引用
- 在宏中定义然后取消定义预处理器变量
- 如何在不取消定义类型的情况下为 C++ 中的类型编写 getter?
- 取消脱壳:使用模板在多行类型定义中添加一个尖括号后的新行
- 在自定义双链接列表中的自定义迭代器的取消运算符,找不到二进制操作员
- 如果我返回const定义的对象,为什么const关键字被取消资格
- 在Ubuntu 12.04.1 LTS libssl-libcrypto上取消定义引用
- 正在取消引用自定义结构字段的迭代器
- 取消定义引用..:从模板类继承
- 自定义 std::shared_ptr 或 boost::shared_ptr 以在 NULL 取消引用时引发异常
- 为什么我的指针在 main 中取消引用后具有不同的值,而不是在我自己的自定义函数中取消引用它时?
- 关于智能指针中取消引用和成员选择运算符的定义
- 我可以显式取消定义特定函数的宏吗?
- 取消引用悬空指针是否是未定义的行为
- 取消引用等于 nullptr 的指针是否是标准的未定义行为?
- C++/Qt定义/取消定义Qt_NO_SESSIONMANAGER宏
- 需要一个头文件,取消定义在windows.h中的所有定义
- 在取消定义宏函数之前,在宏函数中使用/复制宏变量的值:可能吗?
- #定义/#取消定义一个具有特殊含义的标识符是未定义的行为吗