gpt4 book ai didi

c - C 中的全局变量是否是静态的?

转载 作者:太空狗 更新时间:2023-10-29 16:30:17 25 4
gpt4 key购买 nike

C中的全局变量默认是static还是extern
如果全局变量默认为 static 那么这意味着我们可以在单个文件中访问它们,但我们也可以在不同的文件中使用全局变量。
这是否意味着它们默认具有 extern 存储空间?

最佳答案

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

§6.2.2 Linkages of identifiers

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) 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 声明,它也会引用不同的变量。

关于c - C 中的全局变量是否是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4239834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com