使用VS Code任务构建具有自定义包含的C++程序时出现“未定义引用”错误

rbl8hiat  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(249)

我正在尝试编译一个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时,程序运行得很好。然而,这是一个测试,我需要包括头文件只。

jucafojl

jucafojl1#

你的主要问题是
1.您没有在Cars.cpp文件中包含头文件,因此链接器不知道您为该Cars. h文件定义的代码在哪里。
1.在Cars.cpp中,您没有定义在Cars. h中的类中声明的函数
要解决这些问题,必须首先在Cars.cpp文件中包含头文件
所以它看起来像这样..

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

class Cars {

public:
    void printcars() {
        std::cout << "Cars" << std::endl;
    }

};

你需要在Cars.cpp中这样定义函数:

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

void Cars::printcars() {
    std::cout << "Cars" << std::endl;
}

这应该可以修复你的链接器错误。

63lcw9qa

63lcw9qa2#

有几件事不对劲。但最主要的一点是,您已经定义了类Cars两次,一次在cars.h中,一次在cars.cpp中。
cars.cpp应该是这样的

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

void Cars::printcars(){
    std::cout << "Cars" << std::endl;
}

不要定义Cars两次,而是将cars.h包含在cars.cpp中,并对Cars::printcars使用 out of class definition
我不喜欢的另一件事是你的tasks.json文件。不要使用${file},这是您当前正在编辑的文件。我相信你可以看到这可能会导致问题,你只能在编辑main.cpp的时候构建你的代码。其次,不要编译头文件,因此删除"${workspaceFolder}\\include\\*.h"
就像

"args": [
            "-o",
            "${fileBasenameNoExtension}.exe",
            "${workspaceFolder}\\main.cpp",
            "${workspaceFolder}\\include\\*.cpp",
            "-I${workspaceFolder}\\include"
        ],

在我看来是正确的(但我不是VSCodeMaven)。

相关问题