Reputation: 5644
I have read most of the other posts with this title, but I could not find a solution.
I have three files (I know the whole program doesn't make any sense, it is just for test purposes):
main.cpp
#include "Animal.h"
Animal ape;
int main(int argc, char *argv[]){
ape.getRace();
return 0;
}
Animal.h
class Animal{
public:
int getRace();
private:
int race;
};
Animal.cpp
#include "Animal.h"
Animal::Animal(){
race = 0;
}
int Animal::getRace(){
race = 2;
return race;
}
When I run the main.cpp file I get this error:
Undefined symbols for architecture x86_64:
"Animal::getRace()", referenced from:
_main in main-oTHqe4.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
[Finished in 0.1s with exit code 1]
What is wrong here?
Upvotes: 4
Views: 12758
Reputation: 500157
You need to compile and link Animal.cpp
and main.cpp
together, for example:
gcc main.cpp Animal.cpp
It looks like you are not linking against Animal.o
(which the above command would do).
P.S. You also need to declare the default constructor that you are defining in Animal.cpp
:
class Animal{
public:
Animal(); // <=== ADD THIS
int getRace();
private:
int race;
};
Upvotes: 8