C++:体系结构 x86_64 的 undefined symbol

标签 c++

我已经阅读了大多数具有此标题的其他帖子,但找不到解决方案。

我有三个文件(我知道整个程序没有任何意义,只是为了测试目的):

主要.cpp

#include "Animal.h"

Animal ape;

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

    return 0;
}

动物.h

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

动物.cpp

#include "Animal.h"

Animal::Animal(){
    race = 0;
}

int Animal::getRace(){
    race = 2;
    return race;
}

当我运行 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]

这里有什么问题吗?

最佳答案

需要将Animal.cppmain.cpp编译链接在一起,例如:

gcc main.cpp Animal.cpp

看起来你没有链接到 Animal.o(上面的命令会这样做)。

附言您还需要声明您在 Animal.cpp 中定义的默认构造函数:

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

关于C++:体系结构 x86_64 的 undefined symbol ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313267/

相关文章:

iphone - ffmpeg 在 iOS 上的使用

java - 映射类型 : char**& in JNA

c++ - 伪装的指针算术 &(array[0])

c++ - 像数组一样构造 std::string

c++ - 每次执行时,OpenACC 总和减少输出递增总和

c++ - 为什么 std::getline 在使用 operator>> 两次后失败?

c++ - 欧拉计划挑战 3 : Finding the largest prime factor of a large number

c++ - C++仿函数的优势比较

c++ - 如果您以 root 身份运行此 C++ 程序,为什么要花这么长时间才能完成?

c++ - 如何在C++中更清楚地包含头文件