static
, as I think you're using it, is a means of symbol hiding. Functions declared static
are not given global visibility (a Unix-like nm
will show these as 't' rather than 'T'). These functions cannot be called from other translation units.
For C++, static
in this sense has been replaced, more or less, by the anonymous namespace, e.g.,
static int x = 0;
is pretty equivalent to
namespace {
int x = 0;
}
Note that the anonymous namespace is unique for every compilation unit.
Unlike static
, the anonymous namespace also works for classes. You can say something like
namespace {
class Foo{};
}
and reuse that class name for unrelated classes in other translation units. I think this goes to your point 3.
The compiler actually gives each of the symbols you define this way a unique name (I think it includes the compilation time). These symbols are never available to another translation unit and will never collide with a symbol from another translation unit.
Note that all non-member functions declared to be inline
are also by default static
. That's the most common (and implicit) use of static
. As to point 2, defining a static
but not inline
function in a header is a pretty corner case: it's not dangerous per se but it's so rarely useful it might be confusing. Such a function might or might not be emitted in every translation unit. A compiler might generate warnings if you never actually call the function in some TUs. And if that static function has within it a static variable, you get a separate variable per translation unit even with one definition in a single .h
which might be confusing. There just aren't many (non-inline) use cases.
As to point 4, I suspect those people are conflating the static member function meaning of static
with that of the linkage meaning of static
. Which is as good a reason as any for using the anonymous namespace for the latter.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…