Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

preprocessor - Test for empty macro definition

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");

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

Within tracing.h,

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
#  . . .
  • If TRACING has a numerical value (as in #define TRACING 2 ), cpp has a valid expression, and we haven't changed the value.
  • If TRACING has no value (as in #define TRACING ), the preprocessor evaluates #if (+0) to false

The only case this doesn't handle is

  • 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...