First, the word "static" has two meanings in C++: it can refer to the
keyword static
(which in turn has different effects according to where
it is used), or it can refer to the lifetime of a variable: all
variables defined at namespace have static lifetime.
From what you say, I think you are looking for a variable with static
lifetime, which would not be visible outside the single translation unit
where it appears. The preferred way of doing this is to define a
variable in an unnamed namespace:
namespace {
int myWhatever; // No keyword static...
}
Class member variables which are declared static
also have static
lifetime, as do local variables (inside a function) which are declared
static
.
Such a variable is accessible everywhere after its definition in the
translation unit, but no where else. It has a single instance, which
comes into being at the start of the program, and lasts for as long as
the program runs. If it has a constructor, the constructor will be
called before main
(or when the dynamic object is loaded, if dynamic
linking is used), and it's destructor will be called after exit
has
been called (or when the dynamic object is unloaded, if dynamic linking
is used).
With regards to threads, C++11 has a storage class specifier
thread_local
: variables declared with this specifier have one instance
per thread, with a lifetime which is the equivalent of that of the
thread. It will be initialized (constructed) before first use, and
destructed when the thread exits. This is something different from
static.