smwikipedia smwikipedia - 1 year ago 77
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:


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 Source

You cannot put preprocessor directives inside a preprocessor macro.

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

#  define Print(x) Print(x)
#  define Print(x)

// Expands to an empty statement if DEBUG_FLAG were not set.

Good style would deal with semicolons better.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download