beeselmane
beeselmane

Reputation: 1218

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

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!

Upvotes: 4

Views: 1579

Answers (2)

Stephan Lechner
Stephan Lechner

Reputation: 35154

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.

Upvotes: 3

Petr Skocik
Petr Skocik

Reputation: 60068

I'm only getting the warning on clang (if -Wunreachable-code is on), not gcc. A switch silences the warning. Alternatively, pragmas do too (and you can use a _Pragma keyword if you're only against pragma directives).

#include <stdio.h>
#define DEBUG 0
int main()
{
#if 1
    switch(!!DEBUG){
    case 1: puts("hello world");
    case 0:;
    }
#else
    _Pragma("gcc diagnostic push(\"-Wno-unreachable_code\")")
    if(DEBUG){
        puts("hello world");
    }
    _Pragma("gcc diagnostic pop")
#endif

}

Upvotes: 0

Related Questions