启用和禁用代码功能的 C 宏
我之前使用过一个代码库,它有一个用于启用和禁用代码段的宏系统.它看起来像下面这样:
I've used a code base before that had a macro system for enabling and disabling sections of code. It looked something like the following:
#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
然后功能的代码如下所示:
Then the code for the features would look like:
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
}
我的问题(我不记得的部分)是如何定义USING"宏,以便在未将功能定义为IN_USE"或NOT_IN_USE"时出错?如果您忘记包含正确的头文件,可能会出现这种情况.
My question (the part I don't remember) is how to define the 'USING' macro so that it errors if the feature hasn't been defined as 'IN_USE' or 'NOT_IN_USE'? Which could be the case if you forget to include the correct header file.
#define USING( feature ) ((feature == IN_USE) ? 1 : ((feature == NOT_IN_USE) ? 0 : COMPILE_ERROR?))
推荐答案
你的例子已经实现了你想要的,因为 #if USING(x)
如果 USING
未定义.你在头文件中需要的只是
Your example already achieves what you want, since #if USING(x)
will produce an error message if USING
isn't defined. All you need in your header file is something like
#define IN_USE 1
#define NOT_IN_USE 0
#define USING(feature) feature
如果你想确保你也因为做类似的事情而得到一个错误
If you want to be sure that you also get an error just for doing something like
#if FEATURE
或
#if USING(UNDEFINED_MISPELED_FEETURE)
那么你可以这样做,比如说,
then you could do, say,
#define IN_USE == 1
#define NOT_IN_USE == 0
#define USING(feature) 1 feature
但您将无法防止这样的误用
but you won't be able to prevent such misuse as
#ifdef FEATURE
相关文章