我正在尝试编译一个C++程序“test.cpp”,其中包含一个使用VS Code的自定义文件“Cars. h”。然而,它导致了一个构建错误,即使我很确定我做的一切都是正确的。
我的目录结构:
Test
├── .vscode
│ ├── tasks.json
├── include
│ ├── Cars.cpp
│ └── Cars.h
├── test.cpp
test.cpp
#include <iostream>
#include "include/Cars.h"
using namespace std;
int main(){
Cars c;
cout << "Hello!" << endl;
c.printcars();
}
Cars.cpp
#include <iostream>
class Cars{
public:
void printcars(){
std::cout << "Cars" << std::endl;
}
};
Cars.h
#ifndef CARS_H
#define CARS_H
class Cars {
public:
void printcars();
};
#endif
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "buildFile",
"command": "g++",
"args": [
"-o",
"${fileBasenameNoExtension}.exe",
"${file}",
"${workspaceFolder}\\include\\*.cpp",
"${workspaceFolder}\\include\\*.h",
"-I${workspaceFolder}\\include"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
}
]
}
错误:
test.cpp:(.text+0x37): undefined reference to `Cars::printcars()'
collect2.exe: error: ld returned 1 exit status
Build finished with error(s).
* The terminal process terminated with exit code: -1.
* Terminal will be reused by tasks, press any key to close it.
我确信这是一个链接器错误,因为当我包含Cars.cpp而不是Cars.h时,程序运行得很好。然而,这是一个测试,我需要包括头文件只。
2条答案
按热度按时间jucafojl1#
你的主要问题是
1.您没有在Cars.cpp文件中包含头文件,因此链接器不知道您为该Cars. h文件定义的代码在哪里。
1.在Cars.cpp中,您没有定义在Cars. h中的类中声明的函数
要解决这些问题,必须首先在Cars.cpp文件中包含头文件
所以它看起来像这样..
你需要在Cars.cpp中这样定义函数:
这应该可以修复你的链接器错误。
63lcw9qa2#
有几件事不对劲。但最主要的一点是,您已经定义了类
Cars
两次,一次在cars.h
中,一次在cars.cpp
中。cars.cpp应该是这样的
不要定义
Cars
两次,而是将cars.h
包含在cars.cpp
中,并对Cars::printcars
使用 out of class definition。我不喜欢的另一件事是你的tasks.json文件。不要使用
${file}
,这是您当前正在编辑的文件。我相信你可以看到这可能会导致问题,你只能在编辑main.cpp
的时候构建你的代码。其次,不要编译头文件,因此删除"${workspaceFolder}\\include\\*.h"
就像
在我看来是正确的(但我不是VSCodeMaven)。