Consider having the following header file (c++): myclass.hpp
#ifndef MYCLASSHPP_
#define MYCLASSHPP_
namespace A {
namespace B {
namespace C {
class myclass { /* Something */ };
myclass& operator+(const myclass& mc, int i);
}}}
#endif
Consider the implemenation file: myclass.cpp
#include "myclass.hpp"
using namespace A::B::C;
myclass& operator+(const myclass& mc, int i) {
/* Doing something */
}
Consider main file: main.cpp
#include "myclass.hpp"
int main() {
A::B::C::myclass el = A::B::C::myclass();
el + 1;
}
Well, the linker tells me that there is an undefined reference to A::B::C::operator+(A::B::C::myclass const&, int)
What’s the problem here?
Just because you’re
using namespace A::B::Cin the implementation file doesn’t mean that everything declared in there is automatically in theA::B::Cnamespace (otherwise, all definitions would become ambiguous if you wereusingmore than one namespace).myclass.cpp should look something like:
Or (I find this cleaner):
Currently, the compiler thinks you’ve declared one
operator+function in theA::B::Cnamespace, and defined a different function that’s not in a namespace at all, leading to your link error.