c++ - 编译 C++ 时 undefined reference

标签 c++ visual-studio-code include header-files

我的代码与此类似,但问题完全相同:在 VSCode 中编译程序时,我在 Test1.cpp 和 Test2.cpp 中得到“未定义的对 `Test1::v 的引用”。我究竟做错了什么?我对 c++ 有点陌生,所以我刚刚下载了一个扩展,它使我自动成为了一个 c++ 项目。当我使用 Ctrl + Shift + B 运行程序时,它会给我这个错误,但是当我使用 Code Runner 扩展名时,它不会检测到 .cpp 文件。

// Test1.h
#include <iostream>
#include <vector>

using namespace std;

#ifndef TEST1_H
#define TEST1_H

class Test1{
    public:
        Test1();
        static vector<Test1> v;
        int a;

};

#endif
//Test1.cpp
#include "Test1.h"

Test1::Test1(){
    a = 2;
    v.push_back(*this);
}
//Test2.h
#include <iostream>
#include <vector>

using namespace std;

#ifndef TEST2_H
#define TEST2_H

class Test2{
    public:
        Test2();
        double var;
};

#endif
//Test2.cpp
#include "Test2.h"
#include "Test1.h"

Test2::Test2(){
    var = 5;
    Test1::v[0].a += var;
}
//main.cpp
#include <iostream>

#include "Test1.h"
#include "Test2.h"

using namespace std;

int main(int argc, char *argv[])
{
    cout << "Hello world!" << endl;
}

最佳答案

你有 声明 static vector在头文件中,但你需要定义 它在一个cpp文件中。添加:

vector<Test1> Test1::v;
给您的test1.cpp文件。您可以了解更多关于definition对比 declaration here .
还要确保您阅读此内容:Why is "using namespace std;" considered bad practice?

关于c++ - 编译 C++ 时 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62900257/

相关文章:

c++ - 解析文本文件以提取字符串

c++ - 类数组和赋值运算符

c++ - std::map 用于小型稀疏集合

c++ - 寻找将 std::wstring 与 NSLog 一起使用的最便宜的方法

php - 关于 PHP include 语句的问题

javascript - 通过PHP文件include vs script src包含外部脚本有什么好处或弊端?

php - 包含在 PHP 中是无效的

java - 无法在 VS Code 中使用外部 jar

cmd - 缩短 Visual Studio Code 终端中的目录路径

c++ - 如何在 Visual Code Editor 中为 C++ 项目准备/配置开发环境?