Search code examples
c++cstaticlinkage

How did it happen that "static" denotes a function/variable without external linkage in C and C++?


In C static can mean either a local variable or a global function/variable without external linkage. In C++ it can also mean a per-class member variable or member function.

Is there any reference to how it happened that the static keyword that seems totally irrelevant to lack of external linkage is used to denote lack of external linkage?


Solution

  • static is a storage specifier. The word "static" means unchanging. "Storage" refers to where the object is in memory, i.e. its address.

    An object with static storage resides at a constant address.

    It just so happens that an object with extern storage also has a constant address. Due to the way C and C++ programs are linked, it's a necessity. And because extern happens to be the least surprising behavior, it's also the default.

    If you think about it in terms of extern being an extra feature on top of static, I think it makes a bit more sense. It is a bit stupid to declare a function static, since there's no alternative in any fully-compiled language, but the address of a function is static even if it's not externally visible.

    The really inconsistent part, then, is that class members which get shared between different compilation units must be declared static, not extern