【发布时间】:2020-11-26 14:54:35
【问题描述】:
问题:是我,还是 GCC 和 Clang 在评估 C 中的特定全局 char 声明时都没有完全正确的错误消息?
---关于类似问题的一个特别说明是,我正在寻找关于为什么 char 声明会得到这种反应的说明。有相关的问题,是的,但我看到的都是 int 声明。
$ gcc --version gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0
$ clang --version clang 版本 10.0.0-4ubuntu1
考虑以下 C 代码,able.c:
#include <stdio.h>
char able;
able = 'X';
int main(void)
{
printf("%c", able);
}
首先要注意的是,将able 的声明和初始化结合起来效率更高。但是,当通过 GCC 和 Clang 运行时,出现的错误消息在我看来基本上是不正确的消息:
$ clang -Weverything able.c
able.c:5:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
able = 'X';
^
able.c:5:1: error: redefinition of 'able' with a different type: 'int' vs 'char'
able.c:3:6: note: previous definition is here
char able;
^
able.c:3:6: warning: no previous extern declaration for non-static variable 'able' [-Wmissing-variable-declarations]
char able;
^
able.c:3:1: note: declare 'static' if the variable is not intended to be used outside of this translation unit
char able;
^
2 warnings and 1 error generated.
$ gcc -Wall -Wextra -Wpedantic able.c
able.c:5:1: warning: data definition has no type or storage class
5 | able = 'X';
| ^~~~
able.c:5:1: warning: type defaults to ‘int’ in declaration of ‘able’ [-Wimplicit-int]
able.c:5:1: error: conflicting types for ‘able’
able.c:3:6: note: previous declaration of ‘able’ was here
3 | char able;
| ^~~~
这两组消息都抱怨缺少类型说明符,除了类型说明符---char---确实在那里。当声明和初始化消息在该位置组合时,在主函数上方/之前,程序编译。当这对消息放在main函数中时,即使不合并,程序也可以编译。
所以 charable; 语句完全没问题,那为什么会出现这些错误消息?
【问题讨论】:
-
请正确格式化您的代码
-
这在 C 中并不奇怪。全局变量,即出现在函数之外的任何变量只能在初始化时被赋予初始值。它不能用函数外的其他值重新定义,但是,在任何函数内部,我们都可以改变它的值。