C语言 静态 vs 全局

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2271902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:30:12  来源:igfitidea点击:

Static vs global

cstaticglobal

提问by Vijay

If I have a C file like below, what is the difference between iand j?

如果我有一个像下面这样的 C 文件,i和之间有什么区别j

#include <stdio.h>
#include <stdlib.h>

static int i;
int j;

int main ()
{
    //Some implementation
}

采纳答案by CB Bailey

ihas internal linkage so you can't use the name iin other source files (strictly translation units) to refer to the same object.

i具有内部链接,因此您不能使用i其他源文件(严格来说是翻译单元)中的名称来引用同一对象。

jhas external linkage so you can use jto refer to this object if you declare it externin another translation unit.

j具有外部链接,因此j如果您extern在另一个翻译单元中声明它,您可以使用它来引用此对象。

回答by wallyk

iis not visible outside the module; jis globally accessible.

i在模块外不可见;j可全局访问。

That is, another module, which is linked to it, can do

也就是说,另一个链接到它的模块可以做

extern int j;

and then be able to read and write the value in j. The same other module cannot access i, but could declare its own instance of it, even a global one—which is not visible to the first module.

然后能够读取和写入中的值j。同一个其他模块不能访问i,但可以声明它自己的实例,甚至是全局实例——第一个模块不可见。

回答by Hans W

The difference is that ihas internal linkage, and jhas external linkage. This means you can access jfrom other files that you link with, whereas iis only available in the file where it is declared.

区别在于i有内部联动和j有外部联动。这意味着您可以j从链接的其他文件访问,而i仅在声明它的文件中可用。

回答by Ramakrishna

iwill have static linkage, i.e., the variable is accessible in the current file only.

i将具有静态链接,即该变量只能在当前文件中访问。

jshould be defined as extern, that is

j应定义为extern,即

extern int j;

in another header file (.h), and then it will have external linkage, and can be accessed across files.

在另一个头文件(.h)中,然后它会有外部链接,并且可以跨文件访问。

回答by Sravya

Scope of static variable/function is within the same file despite you include the file as part of a different source file.

尽管您将文件作为不同源文件的一部分包含在内,但静态变量/函数的范围在同一个文件中。

Scope of global variable is throughout the files in which it is included. To include the variable in a different source file, we use externbefore the variable declaration. No memory is allocated again for the variable in this case.

全局变量的范围遍及包含它的所有文件。要将变量包含在不同的源文件中,我们extern在变量声明之前使用。在这种情况下,不会再次为变量分配内存。

externis used to declare a C variable without defining it. externkeyword extends the visibility of the C variables and C functions. Since functions are visible through out the program by default, the use of externis not needed in function declaration/definition. Its use is redundant.

extern用于声明一个 C 变量而不定义它。extern关键字扩展了 C 变量和 C 函数的可见性。由于默认情况下函数在整个程序中都是可见的,extern因此在函数声明/定义中不需要使用。它的使用是多余的。