smwikipedia
smwikipedia

Reputation: 64175

How to write a C macro that expands to a `#ifdef... #endif` macro block?

I want to insert some debug output statements into a big C code base. These debug output statements will be controlled by a compiler option switch.

The debug output statement looks like this:

#ifdef DEBUG_FLAG
 Print(someSymbol)
#endif

To save some typing , I am wondering if it is possible to define a simple macro that expands to above debug output statement block?

For example:

#define DBG_MACRO(someSymbol)  (something that can expand to above)

Upvotes: 3

Views: 1035

Answers (3)

Mitch Bogart
Mitch Bogart

Reputation: 11

It is better to make a DB macro that can handle many debug statements. Then you can quickly surround ANY optional debug code with these 4 chars: DB( ) Here's the macro:

#define DEBUG    true    // or false
#ifdef DEBUG
    #define DB(arg) { arg }
#else
    #define DB(arg)
#endif

//  Example uses:
DB(Serial.begin (9600);)

DB(if (!bLastRadarMotion)
   Serial.println("New Motion");)

DB(Serial.print("Room just became UN-Occupied after ");
Serial.print(stillSecondsThreshold);
Serial.println(" seconds.");)

DB(
Serial.print("Room just became UN-Occupied after ");
Serial.print(stillSecondsThreshold);
Serial.println(" seconds.");
)

Upvotes: 1

rici
rici

Reputation: 241671

You cannot put preprocessor directives inside a preprocessor macro.

However, nothing stops you from defining a macro which expands to nothing:

#ifdef DEBUG_FLAG
#  define Print(x) Print(x)
#else
#  define Print(x)
#endif

// Expands to an empty statement if DEBUG_FLAG were not set and
// to a call to Print(something) if DEBUG_FLAG were set.
Print(something);

The above depends on Print being a function which has already been declared/defined. If the macro is defined with DEBUG_FLAG set, the macro is "replaced" with itself, but C preprocessor expansions are not recursive so the expansion only happens once, resulting in a call to Print.

Upvotes: 8

Tordek
Tordek

Reputation: 10872

It is not possible to do it that way; however, it is easy to conditionally define a macro:

#ifdef DEBUG_FLAG
    #define DBG_MACRO(arg) Print(arg)
#else
    #define DBG_MACRO(arg)
#endif

Upvotes: 5

Related Questions