Skip to content
Advertisement

Question about using #define value in if condition and code generation: debug vs release build

Question is related to release and debug build. Something related to this and this

But I have a simple doubt for example if I do following: (file is debug-test.c)

#include <stdio.h>

#define debug  1

int sum (int a, int b){

  if (debug){
    if (a > 0 && b > 0){
      fprintf (stderr, "a(%d) >0 && b(%d)n", a,b);
    }
  }
  return (a+b);
}

int main (void){

  int a = 10, b = 5;
  printf ("a:%d + b:%d = %dn", a, b, sum(a,b));
  
  return 0;
}

So my doubt/question is if I do #define debug 0 will compiler eliminate/optimize out all the code (that if condition) from final binary? Or code will remain in final binary as

if (0){
   .....
}

I have lots of testing and other code that just checks execution in various logical conditions.

What I tried is using gcc -S -Wall -Wextra debug-test.c once with debug set to 0 and once debug set to 1.

With debug set to 1 I get something like following:

        .file   "debug-test.c"
        .text
        .section        .rodata
.LC0:
        .string "a(%d) >0 && b(%d)n"
        .text
        .globl  sum
        .type   sum, @function
sum:
.LFB0:
        .cfi_startproc

When I set debug to 0 I get following

       .file   "debug-test.c"
        .text
        .globl  sum
        .type   sum, @function
sum:
.LFB0:
        .cfi_startproc

I do not really understand output of -S but cursory glance shows that .string "a(%d) >0 && b(%d)n" is not present when I set debug to 0. Other simple thing that I checked is wc -l debug-test.s so for 0 it gives me 61 lines and for 1 it gives me 78 lines. I am not sure I really understand what is happening, will compiler eliminate code or keep it in binary?

Advertisement

Answer

if I do #define debug 0 will compiler eliminate/optimize out all the code (that if condition) from final binary?

Yes, if optimizations are enabled. I just tried your code on x86 gcc -O3 and it removed the whole function call with debug set to zero. Basically it just loads the numbers 5, 10 and 15 as parameters to printf then calls it, and that’s all the program does. https://godbolt.org/z/b3f17rqe4

An issue here is that the compiler might give you spurious warnings “condition is always false” and similar for if(0). Which is why #ifdef debug ... #endif is a better pattern to use.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement