Getting a preprocessor to process a block of code

I have a system in which I specify the level of detail on the command line. In my functions, I check what has been indicated to determine if I am entering the code for the code or not:

#ifdef DEBUG if (verbose_get_bit(verbose_level_1)) { // arbitrary debugging/printing style code generally goes in here, eg: printf("I am printing this because it was specified and I am compiling debug build\n"); } #endif 

I would like to make this less tedious to configure, so here is what I still have:

 // from "Verbose.h" bool verbose_get_bit(verbose_group_name name); // verbose_group_name is an enum #ifdef DEBUG #define IF_VERBOSE_BIT_D(x) if (verbose_get_bit(x)) #else // not debug: desired behavior is the entire block that follows gets optimized out #define IF_VERBOSE_BIT_D(x) if (0) #endif // not debug 

Now I can do it:

 IF_VERBOSE_BIT_D(verbose_GL_debug) { printf("I don't want the release build to execute any of this code"); glBegin(GL_LINES); // ... and so on } 

I like it because it looks like an if-statement, it functions like an if-statement, it clearly indicates that it is a macro, and it does not run in the release build.

I would be sure that the code would be optimized, since it would be wrapped in an if(false) block, but I would prefer some way to force the preprocessor to actually throw away the whole block. It can be done?

+4
source share
3 answers

I can’t figure out how to do this without wrapping the whole block with a macro.

But this may work for your purposes:

 #if DEBUG #define IF_VERBOSE_BIT_D(x) {x} #else #define IF_VERBOSE_BIT_D(x) #endif IF_VERBOSE_BIT_D( cout << "this is" << endl; cout << "in verbose" << endl; printf("Code = %d\n", 1); ) 

Indeed, the compiler should be able to optimize if (0) , but I often do something like this when the code inside the block does not compile at all, when it is not in debug mode.

+2
source

Not as close as you did. Don’t worry, your compiler will fully optimize any if(0) block.

You can, if you want, verify this by writing a program in which you have it, as described and compiling. If you remove the if(false) blocks, it should compile with the same binary code as in the case of the MD5 hash. But this is not necessary, I promise that your compiler will be able to understand this!

+1
source

Just create a condition in the if-statement that starts with "false & &" if you want to completely disable it. If you do not compile without any optimization, the compiler usually removes dead code.

-1
source

Source: https://habr.com/ru/post/1388537/


All Articles