测试空宏定义 [英] Test for empty macro definition

查看:69
本文介绍了测试空宏定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在tracing.hh中,我有一组调试宏。它是否生成代码和输出是由真实源代码中的宏标志控制的:

I've got a set of debug macros in tracing.hh. Whether it generates code and output is controlled by a macro flag in the real source code:

// File:  foo.cc
#define TRACING 0
#include "tracing.hh"
// Away we go . . .
TRACEF("debug message");

标记TRACING应该有一个值;我通常在0和1之间切换。

The flag TRACING should have a value; I usually toggle between 0 and 1.

在tracing.h内,

Within tracing.h,


  • #ifdef跟踪会告诉我已定义跟踪。

  • #if跟踪控制功能宏的定义,例如 TRACEF()

  • #ifdef TRACING will tell me that tracing was defined.
  • #if TRACING controls the definition of functional macros like TRACEF()

但是如果跟踪有没有价值?然后 #if跟踪会产生错误:

But what if TRACING has no value? Then #if TRACING produces an error:

In file included from foo.c:3:
tracing.hh:73:12: error: #if with no expression

我如何测试TRACING是否已定义但没有价值?

How can I test if TRACING is defined but has no value?

推荐答案

有了Matti的建议和更多建议,我认为问题是这样的:如果 TRACING 没有值,则在测试 #if ... Gnu cpp手册
说它必须评估为一个整数表达式,因此即使缺少一个参数,我们也需要一个有效的表达式。我最后遇到的是:

With Matti's suggestion and some more poking, I think the issue is this: if TRACING has no value, we need a valid preprocessor expression in the test #if .... The Gnu cpp manual says it has to evaluate to an integer expression, so we need an expression that is valid even if one of the arguments is missing. What I finally hit on is:

#if (TRACING + 0)
#  . . .




  • 如果 TRACING 具有数字值(如 #define TRACING 2 \n),cpp具有有效表达式,我们没有更改该值。

  • 如果 TRACING 没有值(如 #define TRACING \n ),预处理器将 #if(+0)评估为 false

    • If TRACING has a numerical value (as in #define TRACING 2 \n), cpp has a valid expression, and we haven't changed the value.
    • If TRACING has no value (as in #define TRACING \n), the preprocessor evaluates #if (+0) to false
    • 唯一无法解决的情况是


      • 如果 TRACING 具有非数字值( ON )。 cpp手册说: 不是宏的标识符……都被视为数字零,,其结果为 false 。但是,在这种情况下,将其视为 true 值会更有意义。唯一做正确的事情是布尔文字 true false

      • If TRACING has a non-numerical value (i.e., ON). The cpp manual says "Identifiers that are not macros . . . are all considered to be the number zero," which evaluates to false. In this case, however, it would make more sense to consider this a true value. The only ones that do the right thing are the boolean literals true and false.

      这篇关于测试空宏定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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