产生一个错误,如果没有定义布尔检查宏 [英] Generating an error if checked boolean macro is not defined

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

问题描述

我有几个配置文件每一个包含一些布尔宏定义,被设置为0或1。然后,在我的code,我检查这些宏的值决定$的哪个部分C $ C到激活。现在到了棘手的部分:我想确保我的包含宏定义的头已被列入。

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定义的头文件,编译器将打印的世界!,而我想,而不是它产生错误。

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?

要澄清一下,我不是问<一个href=\"http://stackoverflow.com/questions/2221517/how-to-generate-an-error-and-warning-in-c-$p$pprocessor\">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.

有这将是开发者知道他们的code应包含的要点

The point of having this would be that developers would know that their code should contain

SPECIAL_MACRO(FOO)

其中,在同一时间,检查FOO的布尔值,如果它是一个#如果FOO 语句,$ P $从遗忘列入pvents他们头部定义 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.

推荐答案

谁保持其广泛地配置了一个大code基的同事(喜哈特穆特,库尔特)的#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,如果未定义更换编译器会抱怨。我喜欢它,因为它可以被用来运输多个值不弄乱code与其他 #IFDEF 秒。

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天全站免登陆