可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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 to 0
by default.
回答2:
static
static
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).