C macro to enable and disable code features(启用和禁用代码功能的 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
这篇关于启用和禁用代码功能的 C 宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:启用和禁用代码功能的 C 宏
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07