Search code examples
c++visual-studio-codeincludeheader-files

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

Solution

  • 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?