0

I'm a new user here so I hope I can format everything correctly and be clear. I'm on a Linux machine using gcc 12.2.0 with the -std=c++11 flag, I have 2 files that, among other classes, contain the following (some irrelevant code removed):

TwoDim.h

namespace Dim2 {

class Point {
    private:
        long x,y;

    public:
        explicit Point(long x=0, long y=0);
        long GetX() const;
        long GetY() const;
    };
}

TwoDim.cpp

using namespace Dim2;
std::ostream& operator<<(std::ostream& os, const Point& pt){
    os<<pt.GetX()<<"x "<<pt.GetY()<<"y";
    return os;
}

Where I overloaded operator<<, however when I try to ouput the point's coordinates in my main.cpp file:

#include "TwoDim.h"

int main() {
    Point test(1,2);
    std::cout<<test;
}

the compiler gives me an undefined reference error despite me not having defined any other overload of operator<< (at least not in this namespace). As far as I can tell the function signature is correct so I'm really not sure what's going on here.

I've tried a number of things to solve this

Firstly I tried moving the overload inside TwoDim.h, outside the class

class Point {
    private:
        long x,y;

    public:
        explicit Point(long x=0, long y=0);
        long GetX() const;
        long GetY() const;
    };
}

std::ostream& operator<<(std::ostream& os, const Point& pt){
    os<<pt.GetX()<<"x "<<pt.GetY()<<"y";
    return os;
}

then I tried leaving only the function prototype in TwoDim.h while keeping the implementation in TwoDim.cpp

//In TwoDim.h
class Point {
    private:
        long x,y;

    public:
        explicit Point(long x=0, long y=0);
        long GetX() const;
        long GetY() const;
    };
}


//In TwoDim.cpp
std::ostream& operator<<(std::ostream& os, const Point& pt){
    os<<pt.GetX()<<"x "<<pt.GetY()<<"y";
    return os;
}

But the error persists in both attempts

idk
  • 9
  • 1
  • 1
    [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Jesper Juhl Nov 04 '22 at 20:58
  • 1
    Show all the relevant parts of `TwoDim.h` including the declaration of the operator. To me it looks like you may be implementing the function in a namespace different to the one where it's declared. `using namespace Dim2;` does not result in the following code to be part of the `Dim2` namespace... Btw: Are the semicolons at the end of the class definition missing from your real code too? – fabian Nov 04 '22 at 20:58
  • Scoping the operator with `std::ostream& Dim2::operator<<(std::ostream& os, const Point& pt)` fixed the problem, I really thought that `using namespace` applied to the whole code, thanks fabian! I'd mark your answer but I seem to be unable to – idk Nov 05 '22 at 11:15

0 Answers0