编译C++时未定义的引用
Undefined Reference when compiling C++
我的代码与此代码相似,但问题完全相同:我得到了一个"对"Test1::v"的未定义引用;在VSCode中编译程序时,在Test1.cpp和Test2.cpp中。我做错了什么?我对c++有点陌生,所以我刚刚下载了一个扩展,它使我自动成为c++中的一个项目。当我使用Ctrl+Shift+B运行程序时,它会给我这个错误,但当我使用代码运行程序扩展名运行时,它不会检测到.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
的信息。
还要确保你读到:为什么是";使用命名空间std"被认为是不好的做法?
由于变量是静态的,因此可以在类名前面直接调用变量。所以,你可以做一些类似的事情:
Test1::Test1(){
// v.push__back(*this); // previous
Test1::v.push_back(*this); // now
}
在CCD_ 5中。然后,您将在VS代码上获得一个参考工具提示:
static std::vector<Test1> Test1::v
这证明它已经完成了。
相关文章:
- 编译C++时未定义的引用
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 对 Scalar ::Scalar() 的未定义引用
- 已定义函数时出现 G++ "未定义的引用"错误
- 链接 cmake 时出现未定义的引用错误
- 对复制 CTOR 和 CTOR 的未定义引用
- 错误:未定义对'oboe::AudioStreamBuilder::openStream(oboe::AudioStream**)'的引用
- 右值引用未定义的行为
- 对"vtable for DigitalClock"的未定义引用 - 未定义对"DigitalClock::staticMetaObject"的引用 - Qt
- 函数类型到函数类型的引用:未定义的引用
- avcodec_alloc_context引用未定义,但ffmpeg链接顺序正确
- 从c++调用Fortran子程序,链接时引用未定义
- 枚举引用未定义,但位于包含的头文件中