This is not a name space problem; this is a linker problem.
It's not good to declare a global variable at all. Why not declaring a variable as a member of some class? You can make it static if you want.
Let's forget name spaces: they are irrelevant.
What happen in your case is this: your
value
object is not just declared; it is actually defined in header file; and you include the header file in two or more C++ files (CPP). The compilation units are actually only CPP files. Through include you're trying to create two global objects value: one is included in one CPP file, another in another CPP file, but the object
value
should be unique per executable image.
I do not recommend doing it at all. Global static variables are evil; you can always leave without them. But if you really need one, you need to make only one
definition, but any number of
declarations. Here is how:
Definition: in one CPP file only:
int value;
Declaration, in one *.H file, which can be included in many other (but only different) files:
extern int value;
You should also avoid multiple includes in the same CPP file. Add this to the beginning of all *.h files:
#pragma once
Another possibility (pragma once is not portable) is using
include guards:
#ifndef __MY_UNIT_H
#define __MY_UNIT_H
#pragma once //can combine them
#endif //__MY_UNIT_H
See
http://en.wikipedia.org/wiki/Include_guard[
^].
That will work.
Again, consider avoiding it. This is C++. Use classes for everything, avoid global objects.
—SA