Confusion
Here’s an example of how the two
meanings of static can
cross over each other. All global objects implicitly have static storage
class, so if you say (at file scope),
int a = 0;
then storage for a will be in the
program’s static data area, and the initialization for a will occur
once, before main( ) is entered. In addition, the visibility of
a is global across all translation units. In terms of visibility, the
opposite of static (visible only in this translation unit) is
extern,
which explicitly states that the visibility of the name is across all
translation units. So the definition above is equivalent to
saying
extern int a = 0;
static int a = 0;
all you’ve done is change the
visibility, so a has internal linkage. The storage class is unchanged
– the object resides in the static data area whether the visibility is
static or extern.
Once you get into local variables,
static stops altering the visibility and instead alters the storage
class.
If you declare what appears to be a local
variable as extern, it means that the storage exists elsewhere (so the
variable is actually global to the function). For example:
//: C10:LocalExtern.cpp
//{L} LocalExtern2
#include <iostream>
int main() {
extern int i;
std::cout << i;
} ///:~
//: C10:LocalExtern2.cpp {O}
int i = 5;
///:~
With function names (for non-member
functions), static and extern can only alter visibility, so if you
say
extern void f();
it’s the same as the unadorned
declaration
void f();
static void f();
it means f( ) is visible only
within this translation unit – this is sometimes called file
static.