Reputation: 3652
I have the following two sample c++ files:
File: foo.cc
namespace test_ns {
int x = 100;
}
File: bar.cc
using namespace test_ns;
extern int x;
int main()
{
x = 200;
return 0;
}
I must be doing something really silly as I am getting the following compiler error:
bar.cc:2:17: error: 'test_ns' is not a namespace-name
bar.cc:2:24: error: expected namespace-name before ';' token
However, my main question (after I resolve the namespace error), with the code as is, should I be able to use "x" in bar.cc, or do I need to use additional qualifiers.
Sorry to bother with such a simple issue, but I am pretty stumped with such a simple program.
Thank you, Ahmed.
Upvotes: 1
Views: 6568
Reputation: 171097
Just like every other name in C++, a namespace name must be declared before it can be accessed. When compiling bar.cc
, the compiler doesn't know test_ns
is a namespace name - you haven't provided a declaration for it.
Namespaces and using namespace
aren't magical tricks that let you get around the necessity to declare anything you want to use. To make this work, create a header file:
foo.hh
namespace test_ns {
extern int x;
}
Then #include "foo.hh"
in bar.cc
, and remove extern int x;
from bar.cc
. That will make these two translation units form a valid program. And after you do that, referring to x
in bar.cc
will indeed refer to test_ns::x
(thanks to the using
directive).
As a side note, if you don't remove the extern int x;
from bar.cc
(after you include the header file), it will declare a new global variable ::x
and not refer to test_nest::x
. using namespace
in a source file allows you to define class members without referring to the class's namespace, but namespace-scope entities (variables and functions) always have to be defined inside the namespace or using a qualified name.
Upvotes: 3
Reputation: 59
namespace is defined in a different file. It needs to be defined in a header file which should be included in bar.cc .
Upvotes: 0
Reputation: 234635
They are in different compilation units. You need to declare the namespace in a common header; which you can do using:
namespace test_ns {}
Upvotes: 0