Doug-W
Doug-W

Reputation: 1328

C++ Macro to conditionally compile code?

I want to compile code conditionally based on a macro. Basically I have a macro that looks like (Simplified from the real version):

#if DEBUG
    #define START_BLOCK( x ) if(DebugVar(#x) \
        { char debugBuf[8192];
    #define END_BLOCK( ) printf("%s\n", debugBuf); }
#else
    #define START_BLOCK( x ) (void)0;
    #define END_BLOCK( ) (void)0;
#endif

The issue is that if DEBUG is defined you could do things like:

START_BLOCK( test )
     char str[] = "Test is defined";
     strcpy(debugBuf, str);
END_BLOCK( )

START_BLOCK( foo )
    char str[] = "Foo is defined";
    strcpy(debugBuf, str);
END_BLOCK( )

And everything works fine because each block is within it's own scope. However if DEBUG isn't defined, then you'd get a redefinition of str in the second block. (Well you'd also get debugBuf not defined but that's just a side effect of the simplified example.)

What I'd like to do is to have the #else be something like:

#else
    #define START_BLOCK( x ) #if 0
    #define END_BLOCK( ) #endif
#endif

Or some other method of not having anything between the start / end blocks be compiled. I tried the above, I also tried something along the lines of:

#else
    #define NULLMACRO( ... ) (void)0
    #define START_BLOCK( x ) NULLMACRO(
    #define END_BLOCK( ) )
#endif

without any luck.

Is there a way for this to work? One thought that just occurred to me is that I could maybe abuse the optimizing compiler and use:

#else
    #define START_BLOCK( x ) if(0){
    #define END_BLOCK( ) }
#endif

And trust that it will just compile out the block completely. Are there any other solutions?

Upvotes: 4

Views: 5091

Answers (2)

Tomek
Tomek

Reputation: 4659

Would:

#if DEBUG
    #define START_BLOCK( x ) if(DebugVar(#x) \
        { char debugBuf[8192];
    #define END_BLOCK( ) printf("%s\n", debugBuf); }
#else
    #define START_BLOCK( x ) {
    #define END_BLOCK( ) }
#endif

do?

Upvotes: 1

orlp
orlp

Reputation: 118016

So you want conditional blocks with their own scope?

Here's a quite readable solution that relies on the compiler to optimize it away:

#define DEBUG 1

if (DEBUG) {
    // ...
}

And here is one that is preprocessor-only:

#define DEBUG 1

#ifdef DEBUG
    #define IFDEBUG(x) {x}
#else
    #define IFDEBUG(x)
#endif

IFDEBUG(
    // ...
)

Or manually:

#define DEBUG 1

#ifdef DEBUG
{
    // ...
}
#endif

Upvotes: 5

Related Questions