【问题标题】:GCC: what's the default value when a symbol is defined on command line?GCC:在命令行上定义符号时的默认值是什么?
【发布时间】:2021-09-07 07:20:04
【问题描述】:

根据我对GCC documentation的理解,下面的测试代码显示,命令行上的-DMY_FLAG给符号MY_FLAG一个非零值:

#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!

这是预期的行为吗?如果是,那为什么? MY_FLAG 在-DMY_FLAG 之后的值是多少,即没有明确地为其赋值,例如-DMY_FLAG=1?

【问题讨论】:

    标签: c gcc


    【解决方案1】:

    在命令行上定义的宏的默认值为1:-DMY_FLAG 等价于-DMY_FLAG=1。

    您可以通过以下方式检查:

    #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;
    }
    

    C 标准没有强制要求这种行为,但如果不模仿原始的 pcc,包括 gcc 和 clang 在内的所有其他标准 40 年来,这将需要一个不正当的编译器。

    【讨论】:

    • 谢谢@chqrlie!
    【解决方案2】:

    GCC documentation 表示-D <i>name</i> 的行为是:

    将 name 预定义为宏,定义为 1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 2017-10-28
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2013-06-06
      相关资源
      最近更新 更多