Reputation: 21
I'm trying to overload the shriek (!) operator to return the length of a vector like so: (! because it kind of looks like a lowercase "L", and I wanted a unary operator for the sake of brevity and readability.)
// Vector class in Vector.h
class Vector {
public:
double x,y,z;
/* ... */
double operator ! (); /* Vector length */
/* ... */
}
// Function definition in Vector.cpp
double Vector::operator ! (){
return sqrt(x*x+y*y+z*z);
}
// Main function in main.cpp
#include "vector.h"
int main (int argc, char** argv){
Vector a = Vector(1,2,3);
cout << !a << endl;
}
And the error code that I'm getting from gcc is:
$ gcc -lstdc++ main.cpp
Undefined symbols for architecture ********:
"Vector::operator!()", referenced from:
_main in ********.o
ld: symbol(s) not found for architecture ********
collect2: ld returned 1 exit status
(Note: I couldn't find the answer to this question either due to inexperience with C++ or because I'm trying to do something that violates a very basic tenant of the language that I skipped over due to self-education.)
Upvotes: 1
Views: 391
Reputation: 5241
The compiler is complaining because it doesn't know where the vector method is defined. Try compiling with g++ main.cpp Vector.cpp
.
Explination: In order for your code to work as expected, both your source files need to be compiled and then the compiled objects linked to create the final executable. This is that same as in C.
With C++ (or C with gcc), you can compile individual files using:
g++ -c my_file_1.cpp -o my_file_1.o
g++ -c my_file_2.cpp -o my_file_2.o
If you compile files individually you then need to link the files to create an executable:
g++ my_file_1.o my_file_2.o -o a.out
The command g++ main.cpp Vector.cpp
does all this in one step and does away with the need to create multiple object files (the files with the .o
extension).
Each method for compiling multiple files has its advantages. For example, compiling source files is usually one of the most time expensive exercises in programming. If you compile the files individually then you only have to recompile the object files when you change the source file associated with the object file.
The error in your question was caused in the linking stage (linking is preformed even if you only have 1 files, as long as you don't use the -c
flag). The error basically said that the compiler had the name of the function but couldn't find where the actual compiled code was.
gcc
, try using the command gcc -lstdc++ -lm main.cpp Vector.cpp
.a
to Vector a(1, 2, 3);
.Upvotes: 3