Generating an error if checked boolean macro is not defined(如果未定义检查的布尔宏,则生成错误)
问题描述
我有几个配置文件,每个配置文件都包含一些布尔宏的定义,设置为 0 或 1.然后,在我的代码中,我检查这样一个宏的值来决定激活代码的哪一部分.现在是棘手的部分:我想确保包含我的宏定义的标头已包含在内.
I have several configuration files each one containing the definition of some boolean macro, to be set to 0 or 1. Then, in my code, I check the value of such a macro to decide which part of the code to activate. Now comes the tricky part: I want to be sure that the header containing the definition of my macro has been included.
在以下示例中,如果我忘记包含包含 FOO 定义的头文件,编译器将打印world!",而我希望它生成错误.
In the following example, if I forget to include the header file containing FOO definition, the compiler will print "world!", while I would like instead that it generated an error.
//in the configuration header file
#define FOO 1
//in a cpp file
#if FOO //I would like this to generate an error if I forgot to include the header file
#pragma message "Hello"
#else
#pragma message "world!"
#endif
有可能实现这样的行为吗?怎么样?
Is it possible to achieve such a behaviour? How?
为了澄清,我不是在问 如何如果未定义宏会生成错误,但如果可以转换 #if FOO 行,以便同时检查布尔值并生成错误如果 FOO 没有定义.
To clarify, I am not asking how to generate an error if a macro is not defined, but if it is possible to transform the #if FOO line so that, at the same time, it checks the boolean value and generates an error if FOO is not defined.
这样做的目的是让开发人员知道他们的代码应该包含
The point of having this would be that developers would know that their code should contain
SPECIAL_MACRO(FOO)
同时检查 FOO 的布尔值,就像它是一个 #if FOO 语句一样,并防止他们忘记包含定义 FOO的标头代码>.
which, at the same time, check the boolean value of FOO as if it was an #if FOO statement, and prevents them from forgetting the inclusion of the header defining FOO.
推荐答案
维护大型代码库的同事(嗨 Hartmut,Kurt)遇到了完全相同的问题问题.一个简单的拼写错误,可能在 make 文件中,可能会导致难以追踪的细微错误.他们的解决方案:使用函数宏!在
Colleagues (hi Hartmut, Kurt) who maintained a large code base which was extensively configured with #defines ran exactly into the same problem. A simple mis-spelling, possibly in a make file, could result in subtle errors which were hard to track down. Their solution: Use function macros! In
#if SOME_COND()
// ...
#endif
如果 SOME_COND() 未定义,编译器会报错,而不是简单的 SOME_COND,如果未定义,它将被 0 替换.我喜欢它,因为它可以用于传输多个值,而不会用额外的 #ifdefs 弄乱代码.
the compiler complains if SOME_COND() is not defined, as opposed to a simple SOME_COND which will be replaced by 0 if undefined. I like it because it can be used to transport several values without cluttering the code up with additional #ifdefs.
这篇关于如果未定义检查的布尔宏,则生成错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果未定义检查的布尔宏,则生成错误
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
