“static” vs “extern”
Use Cases in C
In C, variable declaration & definition are implicitly tied together.
Here, definition = storage allocation + possible initialization.
By default, functions and global variables are visible within all linked files.
“extern” keyword allows for declaration sans definition.
But, this would mean that global variables are visible from everywhere.
So, “static” keyword lets us limit the visibility of things within the same file. A static global variable or a static function is “seen” only in the file it’s declared in (so that the user won’t be able to access them. This is encapsulation, a good practice). Thus, “static” forces the lifetime of variables to be equivalent to global.
This means that static variables are stored in static memory as opposed to stack. Thus, having a static variable inside a function would keeps its value between function invocations. This could lead to code being not thread-safe and harder to understand.
Recap: By default, variables declared inside functions have local lifetimes (stack-bound) and using “static” lets us change their storage class to static (aka “global”)