如果选中的布尔宏未定义

如果选中的布尔宏未定义

本文介绍了如果选中的布尔宏未定义,则生成错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个配置文件,每个配置文件包含一些布尔宏的定义,设置为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.

推荐答案

同事(hi Hartmut,Kurt)维护了一个大型代码库,它被广泛配置为 #define 进入同样的问题。一个简单的拼写错误,可能在一个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。我喜欢它,因为它可以用于运输几个值,而不用额外的 #ifdef s。

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.

这篇关于如果选中的布尔宏未定义,则生成错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 14:51