如果未定义检查的布尔宏,则生成错误 [英] Generating an error if checked boolean macro is not defined

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

问题描述

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆