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::C in the implementation file doesn't mean that everything declared in there is automatically in the A::B::C namespace (otherwise, all definitions would become ambiguous if you were using more than one namespace).
myclass.cpp should look something like:
namespace A {
namespace B {
namespace C {
myclass operator+(const myclass& mc, int i) {
// ...
}
}
Or (I find this cleaner):
using namespace A::B::C;
myclass A::B::C::operator+(const myclass& mc, int i) {
// ...
}
Currently, the compiler thinks you've declared one operator+ function in the A::B::C namespace, and defined a different function that's not in a namespace at all, leading to your link error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With