I'm writing a Vector3D class that calls a static method on a VectorMath class to perform a calculation. When I compile, I get this:
bash-3.1$ g++ VectorMath.cpp Vector3D.cpp /tmp/cc5cAPia.o: In function `main': Vector3D.cpp:(.text+0x4f7): undefined reference to 'VectorMath::norm(Vector3D*)' collect2: ld returned 1 exit status
The code:
VectorMath.h:
#ifndef VECTOR3D_H
#include "Vector3D.h"
#endif
class VectorMath {
public:
static Vector3D* calculatePerpendicularVector(Vector3D*, Vector3D*);
static Vector3D* norm(Vector3D*);
static double length(Vector3D*);
};
VectorMath.cpp
#include "VectorMath.h"
Vector3D* norm(Vector3D* vector) { // can't be found by linker
// do vector calculations
return new Vector3D(xHead, yHead, zHead, xTail, yTail, zTail);
}
// other methods
Vector3D.cpp
#include "Vector3D.h"
#include "VectorMath.h"
// ...
// vector implementation
// ...
int main(void) {
Vector3D* v = new Vector3D(x, y, z);
Vector3D* normVector = VectorMath::norm(v); // error here
}
Why can't the linker find the VectorMath::norm
method? At first glance I'd think that I'd need to declare norm like this:
Vector3D* VectorMath::norm(Vector3D* vector) {
but that doesn't help either...
You're missing this:
The
norm
function is part ofVectorMath::
. Without that, you just have a free function.This is more about your design, but why are you using pointers to everything? This is much cleaner:
Take references, you're in C++ so don't write C code. What happens when I call this?
It will either crash, you have to put in a check, in which case, what should it return? This is all cleaned up by using references.
Also, why not just make these members of the
Vector3D
class?Lastly, stack-allocate things. Your code right now has a memory leak:
Change it to this, and use RAII concepts:
And by making
norm
a member function you end up with the very clean code:No pointers, no leaks, all sexy.
You haven't defined
Vector3D::norm
method inVectorMath.cpp
. Instead you've defined a global function namednorm
. What you need to do is qualify the method name in the definition: