Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Undefined symbols for architecture x86_64

Tags:

c++

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?

like image 708
allegutta Avatar asked Feb 14 '23 12:02

allegutta


1 Answers

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;
};
like image 87
NPE Avatar answered Feb 24 '23 03:02

NPE