In C, the literal meaning of static is easy to lead us astray, in fact, it has a role of three.
The first and most important piece of the article: Hide.
When we compile multiple files at the same time, all global variables and functions without a static prefix have global visibility. To understand this sentence, I say for example. We want to compile two source files at the same time, one is A.C and the other is main.c.
Here's what a.c.
Copy Code code as follows:
char a = ' a '; Global variable
void msg ()
{
printf ("hello\n");
}
Here's what main.c.
Copy Code code as follows:
int main (void)
{
extern char A; extern variable must is declared before use
printf ("%c", a);
(void) msg ();
return 0;
}
The results of the program's operation are:
A Hello
you may ask:Why is global variable A and function msg defined in A.C used in MAIN.C? As mentioned earlier, all global variables and functions without a static prefix have global visibility and other source files can be accessed. In this example, a is a global variable, MSG is a function, and neither has a static prefix, so main.c is visible for another source file.
If static is added, the other source files are hidden. For example, add static,main.c to the definition of a and MSG before you can see them. With this feature, you can define a function with the same name and a variable of the same name in different files without worrying about naming conflicts. Static can be used as a prefix for functions and variables, and for functions the static function is limited to hidden