smwikipedia smwikipedia - 4 months ago 16
C Question

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)

Answer

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.
Print(something);

Good style would deal with semicolons better.