关于存储类别和类型的奇怪 GCC 警告
我有一个看起来像
header.h
int TOS;
的头文件该文件仅被一个代码文件
code.c
#include "header.h"
TOS=0;
包含编译 code.c 时 GCC 发出警告
code.c:3:1: warning: dataDefinition has no type or storage类[默认启用] code.c:3:1: 警告:“TOS”声明中的类型默认为“int”[默认启用]
我无法理解此警告的原因。这不是相当于在code.c中声明和定义TOS吗?即
代码.c
int TOS;
TOS=0;
I have a header file that looks like
header.h
int TOS;
This file is being included by just one code file
code.c
#include "header.h"
TOS=0;
When compiling code.c GCC issues a warning
code.c:3:1: warning: data definition has no type or storage class [enabled by default]
code.c:3:1: warning: type defaults to ‘int’ in declaration of ‘TOS’ [enabled by default]
I fail to understand the cause of this warning. Isn't it equivalent to declaring and defining TOS in code.c? i.e.
code.c
int TOS;
TOS=0;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为你在全局范围内定义了
TOS
,这就需要你定义TOS
的类型(它是一个声明),如果没有给出类型,则默认它是int
。这将导致
冲突类型错误
,It is because you define
TOS
in the global scope, which need you to define the type ofTOS
(it is an declaration), if no type was given, by default it isint
.This will cause an
conflicting type error
,在头文件中转发变量的正确方法是
不使用
extern
,否则可能会导致TOS
分配在多个编译单元(.o 文件)中。然后,您可以在一个 .c 文件中给出定义,因为
这将为它保留空间,并且由于它是全局范围内的变量,因此它也会将其初始化为
0
。如果您想让此初始化显式化,或者希望其为0
之外的其他值,则正确的初始化语法(而不是赋值)是现代 C 所不具备的。不允许使用您似乎从某处继承的语法,即隐式类型
int
的全局变量的定义。The correct way to forward a variable in a header file would be
without the
extern
this could otherwise result thatTOS
is allocated in several compilation units (.o files).You'd then give a definition in one .c file as
This would then reserve space for it and since it is a variable in global scope it also would initialize it to
0
. If you want to make this initialization explicit or if you want it to be to another value than0
, the correct syntax for initialization (and not assignment) isModern C doesn't allow the syntax that you seem to have inherited from somewhere, namely a definition of a global variable with implicit type
int
.TOS=0
不是赋值,而是带有初始值设定项的声明(即:定义)。int TOS;
是具有外部链接的暂定定义。当链接器将多个翻译单元链接在一起时,它会折叠相应的对象(=变量的内存)。正如其他地方所述,int
的默认类型是标准后续版本中不存在的 C89 功能。TOS=0
is not an assignment, it's a declaration with an initializer (i.e: a definition).int TOS;
is a tentative definition with external linkage. When the linker links several translation units together, it collapses the corresponding object (=memory for a variable). As said elsewhere, the default type ofint
is a C89 feature absent from later editions of the standard.