VSCode Makefile 不再创建可执行文件,调用 make 时失败

VSCode Makefile no longer creating executable, which fails when make is invoked

所以我正在练习 Linux 的 C++ 项目教程系列。为了创建 makefile,我按 CTR+SHIFT+P 进入 Palet,搜索 make 文件,选择正确的选项,然后选择 C++ 项目。在教程中,该人将 make 文件中的 src 更改为静态路径,即:pwd。那奏效了。当他改回 src 并像他一样将文件移动到 src 文件夹后,执行 make clean,然后 make,我得到这个:

[termg@term-ms7c02 HelloWorldnonVR]$ make
g++ -std=c++11 -Wall -o obj/list.o -c src/list.cpp
g++ -std=c++11 -Wall -o obj/main.o -c src/main.cpp
g++ -std=c++11 -Wall -o HelloWorld obj/list.o obj/main.o 
/usr/bin/ld: obj/main.o: in function `List::List()':
main.cpp:(.text+0x0): multiple definition of `List::List()'; obj/list.o:list.cpp:(.text+0x0): first defined here
/usr/bin/ld: obj/main.o: in function `List::List()':
main.cpp:(.text+0x0): multiple definition of `List::List()'; obj/list.o:list.cpp:(.text+0x0): first defined here
/usr/bin/ld: obj/main.o: in function `List::~List()':
main.cpp:(.text+0x2c): multiple definition of `List::~List()'; obj/list.o:list.cpp:(.text+0x2c): first defined here
/usr/bin/ld: obj/main.o: in function `List::~List()':
main.cpp:(.text+0x2c): multiple definition of `List::~List()'; obj/list.o:list.cpp:(.text+0x2c): first defined here
collect2: error: ld returned 1 exit status
make: *** [Makefile:37: HelloWorld] Error 1
[termg@term-ms7c02 HelloWorldnonVR]$ 

共有三个文件。一个class及其header,然后是main。 list.h 在 src 的 include 子文件夹中。 我目前找不到有关此问题的任何信息,因此将不胜感激。本教程没有制作或 运行 文件的问题。 VSCode 扩展名是 C/C++ Makefile 项目。我的系统是 Manjaro。我确实做了 make clean 并删除了 makefile 以重新开始,以防我敲击键盘或其他东西但同样的结果仍然存在。据我所见,问题是没有创建 HelloWorld 可执行文件。 HelloWorld 是模板中的appname。

将问题缩小到 header。没有构造函数它可以工作,但有它们就不行。

#include <iostream>
#include <vector>
using namespace std;

class List
{
private:
    /* data */
protected:

public:

    void print_menu(); //Prototype
    void print_list();
    void add_item();
    void delete_item();

    vector<string> list;
    string name;
    //constructor
    List(/* args */);
    //destructor
    ~List();
};

List::List(/* args */)
{
}

List::~List()
{
}

关于造成这种情况的原因有什么想法吗?

错误信息告诉你到底是什么问题,如果你学会compiler-ese来解读它:

main.cpp:...: multiple definition of `List::List()'; obj/list.o:list.cpp:...: first defined here

这里说你定义了两次构造函数:一次在 main.cpp 一次在 list.cpp.

而且,在 99.99999% 的情况下,编译器(在这种情况下技术上是链接器)是正确的。你已经在头文件中定义了构造函数和析构函数,并且你在 main.cpp 文件和 list.cpp 文件中都包含了头文件,所以构造函数和析构函数都定义在两者中,只是正如错误所说。

您需要将构造函数和析构函数放在list.cpp源文件中,而不是放在头文件中。

或者,您可以将它们放在 class 本身内,这使它们内联,这样您就不会遇到此问题:

class List
{
private:
    /* data */
protected:

public:
    List(/* args */) {}
    ~List() {}

    void print_menu(); //Prototype

当然,只有当它们足够小且简单到可以像这样内联时,这才有意义。