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

查看:18
本文介绍了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天全站免登陆