【发布时间】: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_cpp_properties.json 用于智能感知语法高亮,不用于编译 - 您要编辑的文件是 tasks.json
标签: c++