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 problem is that if DEBUG defined, you can 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 its own area. However, if DEBUG is not defined, you will get an override of str in the second block. (Well, you would also get debugBuf not defined, but just a side effect of a simplified example.)
What I would like to do is to have #else something like:
#else #define START_BLOCK( x ) #if 0 #define END_BLOCK( ) #endif #endif
Or some other way not to compile between start / end blocks. I tried above, I also tried something like:
#else #define NULLMACRO( ... ) (void)0 #define START_BLOCK( x ) NULLMACRO( #define END_BLOCK( ) ) #endif
no luck.
Is there any way to do this? One thought that occurred to me was that I could abuse the optimizing compiler and use:
#else #define START_BLOCK( x ) if(0){ #define END_BLOCK( ) } #endif
And I believe that he will fully compile the block. Are there any other solutions?