简体   繁体   中英

Undefined Reference when compiling C++

My code is similar to this one, but the problem is exactly the same: I'm getting an "undefined reference to `Test1::v" in Test1.cpp and in Test2.cpp when compilling the program in VSCode. What am I doing wrong? I'm a bit new on c++ so I just downloaded an extension that made me a project in c++ automatically. When I run the program using Ctrl + Shift + B it gives me this error, but when I do it with the Code Runner extension it doesn't detect the.cpp files.

// 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;
}

You have declared the static vector in the header file, but you need to define it in a cpp file. Add:

vector<Test1> Test1::v;

to your test1.cpp file. You can learn more about definition vs declaration here .

Also make sure you read this: Why is "using namespace std;" considered bad practice?

You could prepend the class name to call the variable directly since it's static. So, you could do something like:

Test1::Test1(){
//  v.push__back(*this);       // previous
    Test1::v.push_back(*this); // now
}

in Test1.cpp . You'll then get a reference tooltip on your VS Code:

static std::vector<Test1> Test1::v

Which proves it's done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM