bruin
bruin

Reputation: 1231

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

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?

Upvotes: 3

Views: 609

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 223523

The GCC documentation says the behavior of -D name is to:

Predefine name as a macro, with definition 1.

Upvotes: 0

chqrlie
chqrlie

Reputation: 144949

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.

Upvotes: 3

Related Questions