关于存储类别和类型的奇怪 GCC 警告

发布于 2024-12-08 18:50:26 字数 406 浏览 0 评论 0原文

我有一个看起来像

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

诗酒趁年少 2024-12-15 18:50:27

这是因为你在全局范围内定义了TOS,这就需要你定义TOS的类型(它是一个声明),如果没有给出类型,则默认它是int

这将导致冲突类型错误

char x;
x = 0;

It is because you define TOS in the global scope, which need you to define the type of TOS(it is an declaration), if no type was given, by default it is int.

This will cause an conflicting type error,

char x;
x = 0;
枫以 2024-12-15 18:50:27

在头文件中转发变量的正确方法是

extern int TOS;

不使用 extern,否则可能会导致 TOS 分配在多个编译单元(.o 文件)中。

然后,您可以在一个 .c 文件中给出定义,因为

int TOS;

这将为它保留空间,并且由于它是全局范围内的变量,因此它也会将其初始化为 0。如果您想让此初始化显式化,或者希望其为 0 之外的其他值,则正确的初始化语法(而不是赋值)是

int TOS = 54;

现代 C 所不具备的。不允许使用您似乎从某处继承的语法,即隐式类型 int 的全局变量的定义。

The correct way to forward a variable in a header file would be

extern int TOS;

without the extern this could otherwise result that TOS is allocated in several compilation units (.o files).

You'd then give a definition in one .c file as

int TOS;

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 than 0, the correct syntax for initialization (and not assignment) is

int TOS = 54;

Modern 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.

山川志 2024-12-15 18:50:27

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 of int is a C89 feature absent from later editions of the standard.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文