【问题标题】:Undefined reference error when i try to compile on my home PC [duplicate]当我尝试在家用 PC 上编译时出现未定义的引用错误 [重复]
【发布时间】:2020-02-14 23:07:16
【问题描述】:

好的,所以我尝试更熟悉 C++ 中的 OOP,我得到了以下代码:

//main.cpp
#include <iostream>
#include "ZooAnimal.h"

using namespace std;

int main()
{
    ZooAnimal bozo;
    bozo.set_name(12);
    // bozo.Create("Bozo", 408, 1027, 400);

    // cout << "This animal's name is " << bozo.reptName() << endl;

    // bozo.Destroy();
    cout << "Hello";
}
//ZooAnimal.h
#ifndef ZOOANIMAL_H
#define ZOOANIMAL_H

class ZooAnimal
{
private:
    std::string name;
    int cageNumber;
    int weightDate;
    int weight;

public:
    void Create(std::string, int, int, int);
    void Destroy();
    std::string reptName();
    int daysSinceLastWeighted(int today);
    void set_name(int);
};

#endif //ZooAnimal

最后,

//ZooAnimal.cpp
#include "ZooAnimal.h"
#include <iostream>

void ZooAnimal::Create(std::string a, int b, int c, int d)
{
    //This creates a ZooAnimal Object
    name = a;
    cageNumber = b;
    weightDate = c;
    weight = d;
}

int ZooAnimal::daysSinceLastWeighted(int today)
{
    //calculate how many days have passed since last weight
    return today - weightDate;
}

//clear up the memory
void ZooAnimal::Destroy()
{
    delete &name;
}

// return the animal name
std::string ZooAnimal::reptName()
{
    return name;
}

void ZooAnimal::set_name(int a)
{
    cageNumber = a;
}

所以,当我尝试运行这段代码(当然来自 main.cpp)时,它不会编译,我会在控制台中收到以下消息

C:\Users\<user>\AppData\Local\Temp\ccOiWb7r.o:main.cpp:(.text+0x2e): undefined reference to `ZooAnimal::set_name(int)'
collect2.exe: error: ld returned 1 exit status

我正在使用 MinGW 进行编译,在 Windows 10 机器上工作。奇怪的是,当我尝试在云编辑器(如 repl.it )上运行相同的代码时,它工作得很好,如果我不将我的代码分成多个文件,它再次运行得很好。 知道我能做什么吗?

【问题讨论】:

  • 这是整个错误信息吗?
  • 旁注:为什么你有一个Create 方法(要求创建没有初始化字段的实例,然后是Createed),而不是使用实际的构造函数?跨度>
  • 好的,谢谢大家的帮助。问题是我使用 VS 代码编写和一个名为“Code-runner”的扩展来编译项目,但它只构建了 main.cpp 文件,就是这样。在进行了更多挖掘之后,我有了一个名为 Easy C++ 项目的扩展,它似乎工作正常,但我想我可能不得不很快切换到 CLion。非常感谢你们

标签: c++ oop


【解决方案1】:

您正在构建main.cpp,但不是ZooAnimal.cpp。尝试在 ZooAnimal.cpp 中加入一些明显的语法错误——编译器会抱怨吗?如果没有,你根本就没有编译 ZooAnimal.cpp。如果编译器确实抱怨语法错误,那么您正在编译 ZooAnimal.cpp 但没有将 ZooAnimal.o 传递给链接器,导致未定义符号 set_name()

【讨论】:

    【解决方案2】:

    如果我不将我的代码分成多个文件,它再次运行良好。 知道我能做什么吗?

    这就是你的问题的线索。链接器可以在一个文件中找到void ZooAnimal::set_name(int a) 函数。但是,当您将代码分成单独的文件时,您必须告诉链接器它可以在哪里找到函数的定义。

    您可以按如下方式执行此操作。我正在使用 gcc

    g++ -c file1.cpp  //compile your first source file
    g++ -c file2.cpp  //and now the second
    g++ -o myprog.exe file1.o file2.o //link the 2 object files to get your .exe
    

    作为下一步,您还可以使用生成文件进行编译和构建,您可以在其中指定链接器可以在何处找到您编写的各种函数的所有目标代码。请记住,您可能有多个文件。对于这个练习,它可能有点矫枉过正,但你可以阅读它here

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2015-06-27
      • 2022-01-14
      • 2015-08-21
      相关资源
      最近更新 更多