What is the usage of the “static” keyword in the C programming language?

In the C language, the static keyword can be used to represent two different meanings:

  1. Using the static keyword inside a function: The static keyword can be used to declare variables or functions within a function, in which case it restricts the scope of the variable or function to the source file where they are defined, preventing access from other files. Additionally, static variables persist throughout the program’s runtime rather than being destroyed after the function call ends.
void foo() {
    static int counter = 0;
    counter++;
    printf("%d\n", counter);
}

int main() {
    foo();  // 输出1
    foo();  // 输出2
    return 0;
}
  1. Using the ‘static’ keyword before a global variable: The ‘static’ keyword can be used to restrict the scope of a global variable, allowing the variable to only be accessed within the source file where it is defined and not by other files.
// file1.c
static int global_var = 10;

// file2.c
extern int global_var;  // 这里会报错,因为global_var的作用域被限制在file1.c内
bannerAds