GCC: what's the default value when a symbol is defined on command line?
Asked 07 September, 2021
Viewed 508 times
c gcc
  • 51
Votes

The following test code shows that a -DMY_FLAG on command line gives the symbol MY_FLAG a non-zero value, according to my understanding of GCC documentation:

#include <stdio.h>

void main(void)
{
#if MY_FLAG
    printf("MY_FLAG
");
#else
    printf("hello, world!
");
#endif
}
$ gcc -DMY_FLAG test.c && ./a.out
MY_FLAG
$ gcc -DMY_FLAG=0 test.c && ./a.out
hello, world!
$ gcc -DMY_FLAG=1 test.c && ./a.out
MY_FLAG
$ gcc test.c && ./a.out
hello, world!
$ gcc -Wundef test.c && ./a.out
test.c: In function ‘main’:
test.c:5:5: warning: "MY_FLAG" is not defined, evaluates to 0 [-Wundef]
    5 | #if MY_FLAG
      |     ^~~~~~~
hello, world!

Is this the expected behavior? If yes, then why? What's the value of MY_FLAG after -DMY_FLAG, i.e. without explicitly assign a value to it such as -DMY_FLAG=1?

c gcc

1 Answer