Skip to content

Static

The static keyword is used for following

Hiding a Global Variable within a File Scope

imagine main.c

extern int var; // (1)!

int main () {
    printf("%d", var);
}
  1. extern1 ensures that printf uses var defined inside some other source file.

Imagine definition.c

static int var = 6; // (1)!
  1. static ensures that the var variable is only accessible inside definition.c. If static is removed, we will not get a linker error while trying to compile.

Attempting to compile will cause a linker error.

gcc main.c definition.c -o main.exe
main.c:(.rdata$.refptr.var[.refptr.var]+0x0): undefined reference to `var'
collect2.exe: error: ld returned 1 exit status

Static Variables within Functions2

void foo () {
    static int var = 420;
    var++;
    printf("%d", var);
}

int main () {
    foo(); // (1)!
    foo(); // (2)!
}
  1. Since the declaration is encountered first time, var is created with value 420, incremented to 421 and used. After the function2 returns though, the var remains alive within memory.
  2. Next time when foo() is called, the declaration of var is skipped and the value 421(from previous call to foo()) is incremented to 422.

References


  1. Read more about extern

  2. Read more about functions