ANSI-C 中静态是什么意思
可能的重复:
“静态”在 C 程序中意味着什么?
static
关键字在 C 中意味着什么?
我正在使用 ANSI-C。我在几个代码示例中看到,它们在变量前面和函数前面使用 static
关键字。与变量一起使用的目的是什么?与函数一起使用的目的是什么?
Possible Duplicate:
What does “static” mean in a C program?
What does the static
keyword mean in C ?
I'm using ANSI-C. I've seen in several code examples, they use the static
keyword 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为一个简短的回答,定义变量时
static
关键字有两种用法:1- 使用
static
关键字在文件范围内定义变量,ie 定义的外部函数仅在该文件内可见。任何从其他文件访问它们的尝试都会导致链接时出现无法解析的符号。2- 在函数内的块内定义为静态的变量将在同一代码块的不同调用中持续存在或“生存”。如果它们被定义为初始化,那么它们仅被初始化一次。
static
变量通常保证默认初始化为0
。Just as a brief answer, there are two usages for the
static
keyword when defining variables:1- Variables defined in the file scope with
static
keyword, 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.2- Variables defined as
static
inside 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.static
variables are usually guaranteed to be initialized to0
by default.函数体内的
static
,即用作变量存储分类器,使该变量在函数调用之间保留其值 - 可以说,函数内的静态变量是仅可见的全局变量到该功能。这种static
的使用总是使得它在线程中使用的函数不安全,你应该避免它。另一个用例是在全局范围内使用
static
,即对于全局变量和函数:静态函数和全局变量是编译单元本地的,即它们不会出现在导出表中编译后的二进制对象。因此它们不会污染命名空间。将所有函数和全局变量声明为静态,使其不能从相关编译单元(即 C 文件)外部访问是一个好主意!请注意,静态变量不得放置在头文件中(除非是非常罕见的特殊情况)。static
within 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 ofstatic
always makes the function it is used in thread unsafe you should avoid it.The other use case is using
static
on 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).