I think I hvae a fundamental misunderstanding of namespace and/or static variable. But I have tried this test code (typed by hand, forgive typos)
test.h:
static
at namespace scope is a misnomer, and shouldn't be used. It
means simply that the entity declared static has internal name binding;
in other words, that the same name in other translation units will refer
to a different entity, and in the case of variable definitions, that
there will be a separate instance of the variable in each translation
unit. It has no effect on lifetime. (All variables declared or
defined at namespace scope have static lifetime.)
static
at namespace scope is also deprecated. Don't use it.
With regards to declaring a variable in a header: prefix it with
extern
, and not static
. If a variable is declared extern
, and
there is no initialization, the declaration is not a definition. Of
course, in this case, you must provide a definition somewhere (in a
single source file). Something along the lines of:
extern int testNum = 5;
int testNum = 5;
int testNum; // implicitly initialized with 0.
EDIT:
To clarify somewhat: there is some confusion here between lifetime and name binding:
Do not confuse the keyword static
with static lifetime. (Functions
can be static
, but functions have no defined lifetime in C++; they're
just there.)
The rules regarding these are not very orthognal. Basically, with regards to lifetime:
static
, andstatic
.
regards to lifetime.Objects with static lifetime come into being sometime before main
, and
live until after you return from main
.
With regards to name binding:
static
, in which case they have internal
name binding (but this use of static
is deprecated), or if they are
const
, and are not declared extern
,static
, andFinally, there is the question of whether a declaration is a definition
or not. If it is a definition, memory is allocated and the object is
(or may be) initialized. If it is not a definition, it simply tells the
compiler that there is a definition somewhere else for the entity
(object) declared in the declaration. In general, a variable
declaration is a definition unless it is declared extern
and does
not have an initializer.