Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - the linker can't find my function, which happens to be an overloaded operator [duplicate]

I'm still fairly new to C++, so I apologize in advance if this is has a simple answer. I'm trying to use an overloaded operator. Here's the signature for that operator:

const Vector3D operator/(const Vector3D& lhs, const double rhs)

And here's the method where I'm trying to use it:

OrthonormalBasis::OrthonormalBasis(const Vector3D &a)
{
    Vector3D t;
    w = a / a.length();
    t = getCollinearVector(w);

    //More code goes here
}

When I try to compile, g++ comes back with the following error:

/file/path/orthonormalBasis.cpp:8: undefined reference to 
`operator/(Vector3D const&, double)' 
collect2: ld returned 1 exit status

The operator is defined in Vector3D.cpp, so I do have a definition.

like image 215
Mr Jones Avatar asked Feb 17 '23 16:02

Mr Jones


1 Answers

What you are seeing is a linker error. Linking is a stage of creating an executable that happens after compiling. The job of the linker is to take all references to symbols and resolve them into references to their definitions.

This means that as input to the linker, you have to provide all the symbol definitions. Some of those will come from libraries, and some from .cpp files. Unfortunately, the linker cannot actually parse C++. It expects the compiler to have done that. The compiler than produces a .o file. That .o file contains the results of interpreting symbol definitions and producing stuff the CPU can execute directly. That's the kind of definition the linker needs.

Typically compiling a non-trivial program (i.e. one with multiple .cpp files) into an executable involves creating a bunch of .o files with the compiler, and then linking them together into an executable.

In your case, your symbol is defined in Vector3D.cpp and it is used in orthonormalBasis.cpp. I can also tell from the error that you're using g++ on a Unix platform of some kind. At a minimum the compile and link steps will look like this:

g++ -c Vector3D.cpp
g++ -c orthoNormalBasis.cpp
g++ Vector3D.o orthoNormalBasis.o

I'm betting you're just doing this:

g++ orthoNormalBasis.cpp

This is shorthand for:

g++ -c orthoNormalBasis.cpp
g++ orthoNormalBasis.o

As you can see, this completely misses even trying to compile Vector3D.cpp much less trying to link the resulting .o file into your executable. That's why you're getting that error.

like image 152
Omnifarious Avatar answered Mar 05 '23 18:03

Omnifarious