C language static

In the c language static has two roles,

  1. A variable is declared in a function, so it will not function in each will be called to re-initialize its value.
  2. The second is to declare global static variable or function. For static variable or function declaration, then it is only in this compilation unit visible, other compilation units are not visible. So what is called a compilation unit it? In general, a source document is a compilation c unit, the first document is how to deal with it? When pretreated, pre-processor will include headers are expanded to the current source file, and by a compiler to compile. In this way, we can say that the compiler is concerned, it is not seen the so-called header file, as it had been in the preprocessing stage by the preprocessor to be destroyed, and that is launched . So if you define a static variable in the header file, then include it in every source file, there will be such a variable, but they are not visible to each other. So, if you want to set a global variable across multiple compilation units visible global variables, then you can not define it as the static . Only in a static non-defined source file, and then use extern declared in the header file. Then include this header file is used by the global variable in other compilation units. At the same time, not by defining a non-static variable manner in the header file is achieved, because the header file is expanded into a plurality of source files, resulting in the same variable definition error is repeated in a plurality of source files. In addition, if certain functions of the source file that you do not want to use external, like the same private function cpp, then you should define it as the static. reference

Guess you like

Origin www.cnblogs.com/willhua/p/11764608.html