检查宏内部的宏定义

Check for a definition of a macro inside a macro

假设我有这个代码:

#define NAME MY_APP
#define ENABLE NAME ## _ENABLE

我想检查 ENABLE 扩展到的宏是否已定义,即 MY_APP_ENABLE 是否已定义。这可能使用 C 宏吗?

没有。特别是,建议

#ifdef NAME ## _ENABLE

不会工作,根据6.10.3.4重新扫描和进一步替换,它说

The resulting completely macro-replaced preprocessing token sequence is not reprocessed as a preprocessing directive even if it resembles one, but all pragma unary operator expressions within it are then processed as specified in 6.10.9 below.

您可以使用构造 defined 来检查是否定义了宏,但只能在预处理器表达式中使用它。可以编写扩展到此构造的宏。例如:

#define MY_APP_ENABLED

#define IS_DEFINED(x) defined(x ## _ENABLED)

#if IS_DEFINED(MY_APP)
#error "YES"
#else
#error "NO"
#endif

上面编译时会发出YES。如果未定义 MY_APP_ENABLED,将发出 NO

更新: 以下版本将在 NAME 定义为 MY_APP 时工作。额外的间接级别允许 NAME 在与 _ENABLED:

连接之前扩展为 MY_APP
#define MY_APP_ENABLED

#define IS_DEFINED0(x) defined(x ## _ENABLED)
#define IS_DEFINED(x) IS_DEFINED0(x)

#define NAME MY_APP

#if IS_DEFINED(NAME)
#error "YES"
#else
#error "NO"
#endif