简体   繁体   English

C ++:体系结构x86_64的未定义符号

[英]C++: Undefined symbols for architecture x86_64

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 main.cpp中

#include "Animal.h"

Animal ape;

int main(int argc, char *argv[]){
    ape.getRace();

    return 0;
}

Animal.h Animal.h

class Animal{
    public:
        int getRace();
    private:
        int race;
};

Animal.cpp 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: 当我运行main.cpp文件时,我收到此错误:

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? 这有什么不对?

You need to compile and link Animal.cpp and main.cpp together, for example: 您需要编译并链接Animal.cppmain.cpp ,例如:

gcc main.cpp Animal.cpp

It looks like you are not linking against Animal.o (which the above command would do). 看起来你没有链接Animal.o (上面的命令会这样做)。

PS You also need to declare the default constructor that you are defining in Animal.cpp : PS您还需要声明您在Animal.cpp中定义的默认构造Animal.cpp

class Animal{
    public:
        Animal(); // <=== ADD THIS
        int getRace();
    private:
        int race;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM