Friday, September 9, 2011

C++ namespace: global variables

Suppose you have a "mynamespace.h", which defines your own namespace called "mynamespace", and you have a "mynamespace.cpp", which includes the implementation. Then you include "mynamespace.h" in your main.cpp. You should avoid defining global variables in "mynamespace.h", such as

namespace mynamespace {
double length;

otherwise you will get errors like "multiple definition of ***" during the linking stage. What you should do, is to declare the global variables, for example

namespace mynamespace {
extern double length;

And then you define the global variables in "mynamespace.cpp".


Tim said...

Thanks a lot, this was exactly what I was looking for! Cheers, Tim

Anonymous said...

Man you can't imageine how long I was looking for this. Thanks a lot!