【问题标题】:Type incompatible with itself in GCC 5 when using -Wwrite-strings使用 -Wwrite-strings 时在 GCC 5 中键入与自身不兼容
【发布时间】:2015-12-23 15:05:07
【问题描述】:

考虑:

char f(const char (*x)[4]);

void foo(void) {
    typeof(*"FOO") x[4];
    f(&x);
}

-Wwrite-strings编译:

gcc-5 -c gcc5.c  -Wwrite-strings

你得到:

gcc5.c: In function ‘foo’:
gcc5.c:5:7: warning: passing argument 1 of ‘f’ from incompatible pointer type [-Wincompatible-pointer-types]
     f(&x);
       ^
gcc5.c:1:6: note: expected ‘const char (*)[4]’ 
   but argument is of type ‘const char (*)[4]’
 char f(const char (*x)[4]);
      ^

看起来像 gcc 中的一个错误,除非我遗漏了什么?

注意:-Wwrite-strings 改变文字字符串的类型:

编译C时,给字符串常量类型“const char[length]”

【问题讨论】:

  • 在C中,*"FOO"的类型是char-Wwrite-strings 是否应该改变这一点(使编译器非标准)?如果不是,则错误将&x 的类型显示为const char (*)[4]:没有const
  • 似乎是一个错误。考虑提交错误报告。
  • @PascalCuoq:即便如此,char (*)[4] 可以转换为const char (*)[4],对吗?为什么会是“不兼容的指针类型”?
  • @R_Kapp 不。不可兑换。 const 限定符只能通过一次间接转换后添加,因此char (*)[4] 可以分配给char(*const)[4],但不能分配给const chr(*)[4]
  • @R_Kapp 如果我没记错的话,任何稍微复杂一点的规则都可能违反const 的正确性,并且WG14 认为C++ 对隐式const 的非常复杂的规则集对于C 来说太复杂了。

标签: c gcc


【解决方案1】:

对我来说,这确实是 gcc 5 中的一个错误。

gccdocumentation

-写字符串

编译 C 时,将字符串常量指定为 const char[length] 类型,以便将 1 的地址复制到非 const char * 指针中会产生警告。

所以有了这个声明:

typeof(*"FOO") x[4];

那么当-Wwrite-strings 存在时,&x 的类型为const char (*)[4]。在标准 C 中,&x 的类型为 char (*)[4]

这个小功能:

void foo(void) {
    typeof(*"FOO") x[4];
    printf("%d\n", __builtin_types_compatible_p(typeof(&x), const char (*)[4]));
    printf("%d\n", __builtin_types_compatible_p(typeof(&x), char (*)[4]));
}

打印:

1
0

gcc5.3-Wwrite-strings。所以我们可以看到gcc5.3 正确地将&x 识别为const char (*)[4]-Wwrite-strings

gcc 在调用具有const char (*)[4] 参数的函数时应该接受参数&x。不兼容类型的警告是恕我直言,然后是 gcc 中的一个错误。

(这个错误可能没有出现在以前的gcc 版本中,因为gcc 在以前的gcc 版本中无法(另一个错误)将&x 识别为const char (*)[4]-Wwrite-strings。我用gcc4.9.2gcc-6-20151206测试。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多