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:
First, your misunderstanding has nothing to do with namespaces, it's only about static
. For the rest of this answer I'm going to refer to simply testNum
because the fact it's in a namespace is irrelevant.
I'm also assuming you have another file, probably called test.cpp
, which also includes test.h
and defines the setNum
function.
When a variable or function at namespace-scope (i.e. not a class member or local to a function) is declared static
it means the entity's name is internal to that file. Formally it has "internal linkage", meaning it can't be referred to by name or linked to from other files (it can be indirectly referred to through a pointer or by passing it as an argument to another function.) That means if several files define static int testNum
then each file has its own internal variable with that name, distinct from the testNum
in every other file (in fact one file could have static int testnum
and another could have static double testnum
and another static char* testNum
, they'd all be distinct and internal to each file.) If you put a definition like that in header then every file that includes the header has its own testNum
.
So with static
on your variable in a header you have a different variable called testNum
in every file that includes test.h
. That means if you set testNum
in one file and call a function in a different file which uses testNum
it refers to a different variable, which just happens to have the same name.
Because of this, declaring non-const static
variables in headers is almost always wrong.
Without static
you would have a definition of the testNum
variable in every file that includes test.h
, which is not allowed: every entity must be defined once and once only in your program. The way to solve that is to declare the variable in the header, but not define it, which you do by telling the compiler the variable is extern
:
extern int testNum; // N.B. no "= 1" here
That tells the compiler there is a variable with "external linkage" called testNum
, so when code refers to testNum
it will always mean the same variable (not some name with internal linakge that is a different entity in every file.) After declaring an extern
variable it is your responsibility to ensure there is exactly one definition provided somewhere in the program, so in exactly one file (i.e. not in a header that gets included in multiple files) you define it:
int testNum = 1;