1

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;
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64
Woahthere
  • 55
  • 1
  • 8

2 Answers2

5

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?

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
1

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.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34