"Sandy" wrote:
Hi,
Hello.
I have two files as folllows
file1.cpp
#include<iostream>
using namespace std;
Ewwwwwwwww. That dumps thousands of names from namespace "std"
into the global namespace. Bad idea. (Creates danger of name
collision.) I wish textbook authors would stop telling people
to do that.
namespace {
void show();
void fun() { cout<<"fun called\n"; }
}
int main()
{
show();
return 0;
}
And the name of this namespace is??????????????
If you want to be able to access stuff in that
namespace from other files, you need to name it.
Try this instead:
// file1.cpp
#include<iostream>
using std::cout;
namespace MyNiftyNameSpace
{
void show();
void fun() {cout << "fun called\n";}
}
int main()
{
MyNiftyNameSpace::show();
return 0;
}
file2.cpp
#include<iostream>
using namespace std;
namespace{
void fun();
void show(){
fun();
cout<<"show called\n";
}
}
Once you've named a namespace, you can add to it in other
files, like this:
// file2.cpp
#include<iostream>
using std::cout;
namespace MyNiftyNameSpace
{
void fun();
void show(){
fun();
cout<<"show called\n";
}
}
While trying to run this the linker is giving following message
Undefined first referenced
symbol in file
(anonymous namespace)::fun() file2.o
(anonymous namespace)::show() file1.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
As far as i think, it should be able to find the definitions because
everything here belongs to a single "un-named" namespace.
Then why am i getting the problem?
You were using MULTIPLE un-named namespaces (one per file).
Interection equals null set. (Ie, the namespaces are disjoint.)
But if you name a namespace, you can add stuff to in in many files,
and the linker will hunt-down the missing pieces and link them
together for you.
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant