【问题标题】:Undefined reference to object when compiling with a header file [duplicate]使用头文件编译时对对象的未定义引用[重复]
【发布时间】:2021-09-16 17:25:08
【问题描述】:

编译下面的代码时遇到未定义的引用错误。

这里是 main.cpp:

#include <iostream>
#include "Person.h"

using namespace std;

int main()
{
    Person person1;

    cout << "Age is: " << person1.getAge() << endl;
    cout << "Name is: " << person1.getName() << endl;

    system("PAUSE");

    return 0;
}

这是 Person.cpp:

#include "Person.h"

#include <string>
using namespace std;

int Person::getAge()
{
  return age;
}

string Person::getName()
{
  return name;
}

这是 Person.h:

#ifndef PERSON_H
#define PERSON_H

#include <string>
using namespace std;

class Person
{
   private:
    int age = 25;
    string name = "Jack";

  public:
    int getAge();
    string getName();
};

#endif

错误:

> Executing task: & 'C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\g++.exe' -g d:\Desktop\howdy\main.cpp -o d:\Desktop\howdy\main.exe <

C:\Users\MAC\AppData\Local\Temp\ccbY6HmM.o: In function `main':
d:/Desktop/howdy/main.cpp:32: undefined reference to `Person::getAge()'
d:/Desktop/howdy/main.cpp:33: undefined reference to `Person::getName[abi:cxx11]()'
collect2.exe: error: ld returned 1 exit status
The terminal process "C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -Command & 'C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\g++.exe' -g d:\Desktop\howdy\main.cpp -o d:\Desktop\howdy\main.exe" terminated with exit code: 1.

我将 VS Code 与 GCC (MinGW) 一起使用。我尝试使用 g++ 和 gpp 运行构建任务。我检查了 c_cpp_properties.json。另外,我在这里阅读并关注了文档:https://code.visualstudio.com/docs/cpp/config-mingw

❯ g++ --version
g++.exe (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0

❯ gdb --version
GNU gdb (GDB) 8.1

如果我将类规范和实现放在 main.cpp 中(而不是从 Person.h 中包含它),它可以毫无问题地编译。这让我认为这是一个编译器/链接器问题。有什么想法吗?

【问题讨论】:

标签: c++


【解决方案1】:

这是因为您没有将Person.cpp 作为编译参数。您需要添加 Person.cpp 以及 main.cpp 文件

【讨论】:

  • 有趣!根据您的建议,我将 Person.cpp 包含在 main.cpp 中,它编译时没有问题,太好了! :) 但这让我想知道——怎么会?我一直在翻阅 Gaddis 的教科书和在线教程,以获取带有标题的类实现,但它们都没有在 main.cpp 中包含 .cpp 文件。它们都通过在实现文件和客户端程序中包含标头来工作......
  • @night_train 他的意思不是要将 person.cpp #include 到 main.cpp - 你永远不应该在另一个源文件中#include 一个源文件(只有 #include 头文件)他的意思是两个主要.cpp 和 person.cpp 必须编译成可执行文件。您的日志显示:Executing task: &amp; '...\g++.exe' -g d:\Desktop\howdy\main.cpp -o d:\Desktop\howdy\main.exe 这表明 main.cpp 正在编译,而 person.cpp 没有。如果您使用的是 vs 代码,则需要编辑 tasks.json 以便两个源文件都存在。
  • 感谢@JerryJeremiah 和@ErnestoAlvarez!编辑 tasks.json 解决了这个问题。对于未来的任何人,我专门将args 之一从"${file}" 更改为"${fileDirname}\\*.cpp"
猜你喜欢
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 2023-03-10
  • 2014-04-27
  • 2021-12-26
  • 2016-04-25
相关资源
最近更新 更多