Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang/GCC disable unused code warning as a result of conditional macro

Tags:

c

gcc

I'm writing a program which has debug code which can be disabled by a macro, DEBUG. When set to 1, the debug code should be compiled into the binary, and when set to 0, the debug code should not be.

I am compiling with -Wunreachable-code enabled, and my question results from compiling code such as this:

if (DEBUG) {
    printf("debug string!\n");
}

When debugging is enabled, this will compile fine, as the condition will always evaluate to 1 (true). However, when debugging is disabled (DEBUG=0), I get an unreachable code warning on the printf call on the second line. I am aware this can be solved with the #ifdef/#endif preprocessor directives, however I don't like filling the body of my program with preprocessor directives if it can be avoided.

I am wondering if there is any way I can leave my code with c-style conditionals without using diagnostic pragmas (#pragma GCC diagnostic). Any help would be appreciated, thank you!

like image 765
beeselmane Avatar asked Nov 04 '25 20:11

beeselmane


1 Answers

You could use a pre-proccessor condition instead of a runtime condition:

#if DEBUG == 1
  printf("debug string!\n");
#endif

Thereby, the complete debug-code is "eliminated" without leaving "empty" code blocks. This is much cleaner than letting any debug code, which under changed conditions could behave differently and influence the rest of the code, in production.

Alternatively, if for some reason you must not use pre-processor conditions, you can introduce a log- or trace-function, usually in a separate translation unit. Then you can either react on DEBUEG-state therein. You could even provide two library implementations, an "empty" one for production and a "working" one for deubug, and configure your build to choose the right implementation.

But - as stated above - even the call of an "empty" function could influence compile time optimizations or runtime behaviour. So I'd really suggest to go the pre-processor way.

like image 55
Stephan Lechner Avatar answered Nov 07 '25 10:11

Stephan Lechner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!