Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC: what's the default value when a symbol is defined on command line?

Tags:

c

gcc

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\n");
#else
    printf("hello, world!\n");
#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?

like image 264
bruin Avatar asked Dec 05 '25 14:12

bruin


1 Answers

The default value for a macro defined on the command line is 1: -DMY_FLAG is equivalent to -DMY_FLAG=1.

You can check this with:

#include <stdio.h>

#define xstr(x) #x
#define str(x) xstr(x)

int main(void) {
#ifdef MY_FLAG
    printf("MY_FLAG=%s\n", str(MY_FLAG));
#else
    printf("MY_FLAG is not defined\n");
#endif
    return 0;
}

The C Standard does not mandate this behavior but it would take a perverse compiler to not mimic the original pcc as all others have for 40 years including gcc and clang.

like image 146
chqrlie Avatar answered Dec 07 '25 06:12

chqrlie



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!