0x4*_*121 1 c c++ macros c-preprocessor preprocessor-directive
我之前使用过一个代码库,它有一个用于启用和禁用代码部分的宏系统。它看起来像下面这样:
#define IN_USE X
#define NOT_IN_USE _
#if defined( WIN32 )
#define FEATURE_A IN_USE
#define FEATURE_B IN_USE
#define FEATURE_C NOT_IN_USE
#elif defined( OSX )
#define FEATURE_A NOT_IN_USE
#define FEATURE_B NOT_IN_USE
#define FEATURE_C IN_USE
#else
#define FEATURE_A NOT_IN_USE
#define FEATURE_B NOT_IN_USE
#define FEATURE_C NOT_IN_USE
#endif
Run Code Online (Sandbox Code Playgroud)
然后功能的代码将如下所示:
void DoFeatures()
{
#if USING( FEATURE_A )
// Feature A code...
#endif
#if USING( FEATURE_B )
// Feature B code...
#endif
#if USING( FEATURE_C )
// Feature C code...
#endif
#if USING( FEATURE_D ) // Compile error since FEATURE_D was never defined
// Feature D code...
#endif
}
Run Code Online (Sandbox Code Playgroud)
我的问题(我不记得的部分)是如何定义“USING”宏,以便在该功能尚未定义为“IN_USE”或“NOT_IN_USE”时出错?如果您忘记包含正确的头文件,可能会出现这种情况。
#define USING( feature ) ((feature == IN_USE) ? 1 : ((feature == NOT_IN_USE) ? 0 : COMPILE_ERROR?))
Run Code Online (Sandbox Code Playgroud)
您的示例已经实现了您想要的功能,因为#if USING(x)如果USING未定义,则会产生错误消息。您在头文件中所需要的只是
#define IN_USE 1
#define NOT_IN_USE 0
#define USING(feature) feature
Run Code Online (Sandbox Code Playgroud)
如果你想确保你也会因为做类似的事情而得到一个错误
#if FEATURE
Run Code Online (Sandbox Code Playgroud)
或者
#if USING(UNDEFINED_MISPELED_FEETURE)
Run Code Online (Sandbox Code Playgroud)
那么你可以做,说,
#define IN_USE == 1
#define NOT_IN_USE == 0
#define USING(feature) 1 feature
Run Code Online (Sandbox Code Playgroud)
但你将无法防止这样的误用
#ifdef FEATURE
Run Code Online (Sandbox Code Playgroud)