What does static mean in ANSI-C [duplicate]

吃可爱长大的小学妹 提交于 2019-11-27 07:47:46
Roux hass

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.

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 of 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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!