Your code did not work, because you defined a variable two times in namespace scope in a header file. So in the moment your header file was included in two different files, the compiler saw that in the same scope you tried to define two variables with the same name. That was a name collision and ended up in an error message saying more or less what i am.
Through the static keyword you made cout an object without external linkage solving this prob. BUT. I am not sure if this way of using the static keyword is deprecated (still accepted but could be remove in further verions of C++ standards). Using it for global variables is definitivly deprecated. As far as i know 'global' is just a special case of namespace scope.
In fact static keyword for global variables just say to the compiler that a variable has no external linkage. Thats why no name collision occur if you define it in more than one variable. The Linker does not even look if there is a second cout in main.cpp or Example.cpp.
You could achieve the same with unnamed namespaces, which member you can only access in the file they are defined (because if a namespace has no name, you can’t explicitly use a using directive or using declaration to make the names available elsewhere) You can use it like this:
example.h (based on my own test code)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#ifndef __example_h
#define __example_h
#include <string>
namespace example
{
class CommandConsole {
private:
std::string input;
public:
CommandConsole & operator<< (std::string);
std::string last() const { return input; }
};
namespace {
CommandConsole cout;
}
}
#endif
| |
In my oppinion it is defintivly better to define your cout object in your Example.cpp and make a reference declaration in your header file like this:
in Header:
|
extern CommandConsole cout;
| |
in Example.cpp
This way the variable will be in memory just once.
Hope its correct now, Maikel