I get why static local variables are called “static” — we want them to be allocated in static memory! But what is the reason for calling functions and variables we want restricted to the current file “static”? I don’t see the connection; either way, they’re allocated in static memory, right?
static keyword is overloaded with multiple meanings, and which meaning applies depends on where it appears. It affects both the storage duration (lifetime) of an object and the linkage of the identifier associated with an object of function declared at file scope.
Refer to “6.2.2 Linkages of Identifiers” and “6.2.4 Storage Duration of Objects” in the online draft of the C11 standard for details.
Note that the
static keyword only affects linkage for function and object identifiers declared at file scope (outside the body of any function) – identifiers declared within a function or block (and without the
extern keyword) have no linkage.
I get why static local variables are called “static” — we want them to be allocated in static memory
Um, no. The
static keyword dates back to the early days of the C programming language, where it can both specify the scope and lifetime of the item.
Languages “inspired” by C have copied the
static keyword and used it with its “lifetime” meaning: static members typically have a lifetime of the entire execution of the application.
In C, and depending on use, the
extern keywords denote either the scope or the lifetime of a variable
IMHO, this was (and continues to be) a mistake. It seems illogical that use of
static on a variable at file-scope has a different meaning than when used on a function-scope variable.
At least C++ has addressed this, by using
private for scope, while retaining
static for lifetime.