Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ problems when lnker finalizes compilation process on overloaded operator [duplicate]

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?

like image 872
Andry Avatar asked Mar 04 '26 14:03

Andry


1 Answers

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.

like image 89
Cameron Avatar answered Mar 07 '26 05:03

Cameron