Reputation:
I am learning C++ and have been given an assignment to create a Vector3D class. When I try to compile main.cpp using G++ on OSX I get the following error message. Why would this be?
g++ main.cpp
Undefined symbols for architecture x86_64:
"Vector3DStack::Vector3DStack(double, double, double)", referenced from:
_main in cc9dsPbh.o
ld: symbol(s) not found for architecture x86_64
main.cpp
#include <iostream>;
#include "Vector3DStack.h";
using namespace std;
int main() {
double x, y, z;
x = 1.0, y = 2.0, z = 3.0;
Vector3DStack v (x, y, z);
return 0;
}
Vector3DStack.h
class Vector3DStack {
public:
Vector3DStack (double, double, double);
double getX ();
double getY ();
double getZ ();
double getMagnitude();
protected:
double x, y, z;
};
Vector3DStack.cpp
#include <math.h>;
#include "Vector3DStack.h";
Vector3DStack::Vector3DStack (double a, double b, double c) {
x = a;
y = b;
z = c;
}
double Vector3DStack::getX () {
return x;
}
double Vector3DStack::getY () {
return y;
}
double Vector3DStack::getZ () {
return z;
}
double Vector3DStack::getMangitude () {
return sqrt (pow (x, 2) * pow (y, 2) * pow (z, 2));
}
Upvotes: 8
Views: 21758
Reputation: 159
I had ran into a similar issue when writing my own implementation of a hashTable with templates. In your main.cpp, just include "Vector3DStack.cpp", which includes Vector3DStack.h, instead of just including Vector3DStack.h.
In my case, since templates, as we know, are evaluated at compile time, having templatized (including fully specialized) methods in the class as part of the cpp file (where they are defined) need to be known to the compiler. Some of the C++ gotchas.. so much to remember, easy to forget the little things.
Mostly likely you've already got our solution, thanks to the answers posted earlier, but my $0.02 anyways.
Happy C++ Programming!
Upvotes: 4
Reputation: 26204
Pass the implementation of Vector3D
to the compiler:
g++ main.cpp Vector3DStack.cpp
This will produce executable called a.out
on Linux and Unix systems. To change the executable name use -o
option:
g++ -o my_program main.cpp Vector3DStack.cpp
This is the simplest possible way of building your program. You should learn a bit more - read about make
program, or even cmake.
Upvotes: 7
Reputation: 5145
You have to compile and link your Vector3DStack.cpp
as well. Try:
g++ main.cpp Vector3DStack.cpp -o vectortest
This should create an executable called vectortest
.
Upvotes: 24