定义一个宏,然后取消定义之前未定义的宏

Define a macro then undefine it if it was previously undefined

本文关键字:定义 取消 未定义 然后 一个      更新时间:2023-10-16

我包括头文件,需要某些专业处理器#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

问题:

  1. 将上述工作,即恢复所有宏定义(或缺乏)到他们之前的状态?

  2. 有没有更简单的解决方案?

  3. 如果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
  1. 我有#pragma push_macro/pop_macro("macro_name")在脑海中,但它可能只在gcc和MS vc++中工作
  2. 是的,这很重要,如果用不同的值再次定义它,你会得到一个警告。正如你所说,你可以用#ifndef屏蔽它。