C language static modifier function in detail

  • 2020-04-02 01:16:36
  • OfStack

In C, the literal meaning of static can easily lead us astray, but it actually serves three purposes.
The first and most important one to introduce it is to hide.
When we compile multiple files at the same time, all global variables and functions that are not prefixed with static are globally visible. To understand this sentence, let me give you an 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 says


char a = 'A'; // global variable
void msg() 
{
    printf("Hellon"); 
}

Here's what main.c looks like

int main(void)
{    
    extern char a;    // extern variable must be declared before use
    printf("%c ", a);
    (void)msg();
    return 0;
}

The result of running the program is:
A Hello!

You may ask: why are the global variables a and the function MSG defined in a.c used in main.c? As mentioned earlier, all global variables and functions that are not prefixed with static are globally visible and accessible to other source files. In this example, a is a global variable and MSG is a function, and both are not prefixed with static, so they are visible to the other source main.c.

If you add static, it will be hidden from other source files. For example, if you put static before the definition of a and MSG, main.c will not see them. This feature allows you to define functions and variables with the same name in different files without worrying about naming conflicts. Static can be used as a prefix for functions and variables. For functions, Static is only used to hide


Related articles: