I have two files once is named as test.cpp and another as ani.cpp.
test.cpp is as follows:
#include<iostream>
namespace Anirudh{
void start(){
std::cout<<"This is the start function of the namespace Anirudh\n";
}
}
and the file ani.cpp is as follows
#include<iostream>
using namespace Anirudh;
int main(){
start();
return 0;
}
and this is what I am doing on the terminal
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ g++ -c test.cpp
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ g++ test.o ani.cpp
ani.cpp:3: error: ‘Anirudh’ is not a namespace-name
ani.cpp:3: error: expected namespace-name before ‘;’ token
ani.cpp: In function ‘int main()’:
ani.cpp:6: error: ‘start’ was not declared in this scope
anirudh@anirudh-Aspire-5920:~/Desktop/testing$
This is the first time I am trying to define my own namespace in C++ and using开发者_如何学Python it in another code. I got my code running after #include "test.cpp" in my ani.cpp file but I want to link the object code of test.cpp with ani.cpp rather than including it inside ani.cpp
I have even tried extern namespace Anirudh; but that didn't work. Of-course there is a proper way to link them which I do not know right now. So please enlighten me. Thanks in advance.
Within ani.cpp you never told the compiler that there's a namespace Anirudh somewhere else in the program prior to doing the using. If you're used to other module systems this probably seems quirky.
What you can do is declare the namespace+function prior to calling it, with these lines before the using namespace in ani.cpp
namespace Anirudh{
void start();
}
Often these declarations would be wrapped up in a header but that's probably not needed for this simple example.
What about prototyping the function a la:
namespace Anirudh {
void start();
} // namespace Anirudh
int main(...){
//...
If you don't have header file, then the least you've to do is : write the prototype of your function in ani.cpp before calling it as,
using namespace Anirudh;
void Anirudh::start();
int main(){
start();
return 0;
}
加载中,请稍侯......
精彩评论