C ++ Macro for conditional code compilation?

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?

+4
source share
2 answers

So you want conditional blocks with your scope?

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

 #define DEBUG 1 if (DEBUG) { // ... } 

And here is just the preprocessor:

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

Or manually:

 #define DEBUG 1 #ifdef DEBUG { // ... } #endif 
+5
source

Will be:

 #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 

make?

+1
source

All Articles