Test to identify empty macros

I have a set of debug macros in tracing.hh. Regardless of whether it generates code and outputs, a controlled macro flag in real source code:

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

The TRACING flag must have a value; I usually switch between 0 and 1.

Inside tracing.h,

  • #ifdef TRACING will tell me that the trace is defined.
  • #if TRACING controls the definition of function macros like TRACEF()

But what if TRACING doesn't matter? Then #if TRACING throws an error:

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

How can I check if TRACING is defined but doesn't matter?

+20
c-preprocessor preprocessor
Nov 04 '10 at 23:30
source share
3 answers

With Matti's suggestion and some other comments, I think the problem is this: if TRACING doesn't matter, we need the correct preprocessor expression in the #if... test #if... The gnu cpp manual says that it should be evaluated as an integer expression, so we need the correct expression, even if one of the arguments is missing. What I finally hit is:

 #if (TRACING + 0) # . . . 
  • If TRACING has a numeric value (as in #define TRACING 2 \n) , cpp has a valid expression, and we have not changed the value.
  • If TRACING does not matter (as in #define TRACING \n ), the preprocessor evaluates #if (+0) to false

The only case this does not handle is

  • If TRACING has a non-numeric value (i.e. ON ). The cpp manual says: "Identifiers that are not macros ... all count as zero", which means false . In this case, however, it would be more reasonable to consider this true value. The only ones that do the right thing are the logical literals true and false .
+24
Nov 08 '10 at 19:06
source share

Late to the party, but I found a good trick to distinguish

 #define TRACING 0 

from

 #define DTRACING 

like this:

 #if (0-TRACING-1)==1 && (TRACING+0)!=-2 #error "tracing empty" #endif 

If TRACING empty, the expression evaluates to 0--1 => 1 .

If TRACING is 0, the expression evaluates to 0-0-1 => -1

I added an additional check in case of TRACING==-2 which will make the first test pass.

This does not work for string literals, of course.

+3
Jan 31 '18 at 10:36
source share

Would

 #if defined(TRACING) && !TRACING 

do the trick?

0
Nov 04 '10 at 23:40
source share



All Articles