简体   繁体   English

C中与static关键字的内部链接

[英]Internal linkage with static keyword in C

I know static is an overloaded keyword in C. Here, I'm only interested in its use as a keyword to enforce internal linkage. 我知道static是C中的一个重载关键字。在这里,我只关心它作为一个关键字用来强制内部链接。

If you have a global variable declared in a .c file, what is the difference between using static and not using static ? 如果在.c文件中声明了全局变量,那么使用static和不使用static什么区别? Either way, no other .c file has access to the variable, so the variable is basically "private" to the file, with or without the static keyword. 无论哪种方式,没有其他.c文件可以访问该变量,因此该变量基本上是文件的“私有”,有或没有static关键字。

For example, if I have a file foo.c , and I declare a global variable: 例如,如果我有一个文件foo.c ,并且我声明了一个全局变量:

int x = 5;

That variable x is only available to code inside foo.c (unless of course I declare it in some shared header file with the extern keyword). 该变量x仅适用于foo.c代码(当然,除非我在某个带有extern关键字的共享头文件中声明它)。 But if I don't declare it in a header file, what would be the difference if I were to type: 但是如果我没有在头文件中声明它,那么如果我输入的话会有什么不同:

static int x = 5 . static int x = 5

Either way, it seems x has internal linkage here. 无论哪种方式,似乎x在这里有内部联系。 So I'm confused as to the purpose of static in this regard. 所以我对static的目的很困惑。

If you have a global variable declared in a .c file, what is the difference between using static and not using static ? 如果在.c文件中声明了全局变量,那么使用static和不使用static什么区别? Either way, no other .c file has access to the variable [...] 无论哪种方式,没有其他.c文件可以访问变量[...]

A different file could declare x : 一个不同的文件可以声明 x

extern int x;

That would allow code referencing x to compile, and the linker would then happily link those references to any x it finds. 这将允许引用x代码进行编译,然后链接器会愉快地将这些引用链接到它找到的任何x

static prevents this by preventing x from being visible outside of its translation unit. static通过阻止x在其翻译单元外部可见来防止这种情况。

There is only one "namespace", so to speak, in C. Without the "static" keyword you are not protected from another file using the name "x" (even if you do not make it visible in your own library's header). 只有一个“命名空间”,可以这么说,在C.没有“static”关键字,您不会使用名称“x”保护其他文件(即使您没有在自己的库的标题中显示它)。

Try to link together several C files containing a non-static variable x (interleaving read and write accesses from functions in each file), and compare with the situation where these variables are declared static. 尝试将包含非静态变量x几个C文件链接在一起(对每个文件中的函数进行交错读写访问),并将这些变量声明为静态的情况进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM