C语言 ANSI-C 中的静态是什么意思
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4576607/
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
What does static mean in ANSI-C
提问by Sency
Possible Duplicate:
What does “static” mean in a C program?
可能的重复:
C 程序中的“静态”是什么意思?
What does the statickeyword mean in C ?
staticC中的关键字是什么意思?
I'm using ANSI-C. I've seen in several code examples, they use the statickeyword in front of variables and in front of functions. What is the purpose in case of using with a variable? And what is the purpose in case of using with a function?
我正在使用 ANSI-C。我在几个代码示例中看到,它们static在变量和函数前使用关键字。与变量一起使用的目的是什么?与函数一起使用的目的是什么?
回答by Roux hass
Just as a brief answer, there are two usages for the statickeyword when defining variables:
简单回答一下,static关键字在定义变量时有两种用法:
1- Variables defined in the file scope with statickeyword, i.e.defined outside functions will be visible only within that file. Any attempt to access them from other files will result in unresolved symbol at link time.
1- 使用static关键字在文件范围内定义的变量,即定义在函数之外的变量仅在该文件内可见。任何从其他文件访问它们的尝试都将导致链接时无法解析符号。
2- Variables defined as staticinside a block within a function will persist or "survive" across different invocations of the same code block. If they are defined initialized, then they are initialized only once. staticvariables are usually guaranteed to be initialized to 0by default.
2- 定义为static函数内块内的变量将在同一代码块的不同调用中保持或“存活”。如果它们被定义为初始化,那么它们只被初始化一次。static变量通常保证0被默认初始化。
回答by datenwolf
staticwithin the body of a function, i.e. used as a variable storage classifier makes that variable to retain it's value between function calls – one could well say, that a static variable within a function is global variable visible only to that function. This use of staticalways makes the function it is used in thread unsafeyou should avoid it.
static在函数体内,即用作变量存储分类器,使该变量在函数调用之间保留其值——可以说,函数内的静态变量是仅对该函数可见的全局变量。这种使用static总是使得它在线程中使用的函数不安全,你应该避免它。
The other use case is using staticon the global scope, i.e. for global variables and functions: static functions and global variable are local to the compile unit, i.e. they don't show up in the export table of the compiled binary object. They thus don't pollute the namespace. Declaring static all the functions and global variables not to be accessible from outside the compile unit (i.e. C file) in question is a good idea! Just be aware that static variables must not be placed in header files (except i very rare special cases).
另一个用例是static在全局范围内使用,即对于全局变量和函数:静态函数和全局变量是编译单元的局部变量,即它们不会出现在编译后的二进制对象的导出表中。因此它们不会污染命名空间。将所有函数和全局变量声明为不可从编译单元(即 C 文件)外部访问的静态变量是一个好主意!请注意,不得将静态变量放在头文件中(除非是非常罕见的特殊情况)。

