C中的全局变量是静态的还是不是静态的? [英] Global variables in C are static or not?

查看:145
本文介绍了C中的全局变量是静态的还是不是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下C是static还是extern中的全局变量?
如果默认情况下全局变量为static,则意味着我们可以在单个文件中访问它们,但是我们也可以在其他文件中使用全局变量.
这是否暗示他们默认情况下具有extern存储空间?

Are global variables in C static or extern by default?
If global variables are by default static then it means that we would be able to access them in a single file, but we can use global variables in different files as well.
Does this imply that they have extern storage by default?

推荐答案

如果未指定存储类(即externstatic关键字),则默认情况下,全局变量具有外部链接.根据C99标准:

If you do not specify a storage class (that is, the extern or static keywords), then by default global variables have external linkage. From the C99 standard:

§6.2.2标识符的链接

3)如果对象或函数的文件作用域标识符的声明包含存储类说明符static,则该标识符具有内部链接.

3) If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

5)如果一个函数的标识符声明没有存储类说明符,则其链接的确定与使用存储类说明符extern声明的完全相同.如果对象的标识符声明具有文件范围且没有存储类说明符,则其链接是外部的.

5) If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

因此,即使您未指定extern关键字,全局变量仍然可以被其他源文件(所谓的翻译单元)访问,因为它们仍然可以具有extern相同变量的声明.如果使用static关键字指定内部链接,则即使在另一个源文件中存在用于同一变量名称的extern声明,它也会引用不同的变量.

So even if you don't specify the extern keyword, globals can still be accessed by other source files (so-called translation units), because they can still have an extern declaration for the same variable. If you use the static keyword to specify internal linkage, then even in the presence of an extern declaration for the same variable name in another source file, it will refer to a different variable.

这篇关于C中的全局变量是静态的还是不是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆