简体   繁体   中英

C++ static variable in header file getting LNK error 2001

I have myself a very basic program. I am trying to create a static vector in a class, which can then be accessed around my whole program which just creating an instance of that class which has the stored static vector.

here is my test program

testClass.h

#pragma once

#include <vector>

class TestClass
{
public:
    TestClass();
    ~TestClass();

    static void AddNumber(int number);

    static std::vector<int> Numbers;
};

testClass.cpp

#include "TestClass.h"

TestClass::TestClass()
{
    Numbers.push_back(1);
    Numbers.push_back(2);
    Numbers.push_back(3);
}

TestClass::~TestClass()
{

}

void TestClass::AddNumber(int number)
{
    Numbers.push_back(number);
}

main.cpp

#include "TestClass.h"
#include <iostream>

int main()
{
    TestClass testClass;

    testClass.AddNumber(4);

    for (int i = 0; i < testClass.Numbers.size(); i++)
    {
        std::cout << "Number at " << i << ", is : " << testClass.Numbers.at(i) << std::endl;
    }

    std::cin.get();
}

When I compile I am getting

Error   2   error LNK2001: unresolved external symbol "public: static class std::vector<int,class std::allocator<int> > TestClass::Numbers" (?Numbers@TestClass@@2V?$vector@HV?$allocator@H@std@@@std@@A)   c:\Users\mainUser\documents\visual studio 2013\Projects\C++StaticClass\C++StaticClass\main.obj  C++StaticClass
Error   3   error LNK2001: unresolved external symbol "public: static class std::vector<int,class std::allocator<int> > TestClass::Numbers" (?Numbers@TestClass@@2V?$vector@HV?$allocator@H@std@@@std@@A)   c:\Users\mainUser\documents\visual studio 2013\Projects\C++StaticClass\C++StaticClass\TestClass.obj C++StaticClass
Error   4   error LNK1120: 1 unresolved externals   c:\users\mainUser\documents\visual studio 2013\Projects\C++StaticClass\Debug\C++StaticClass.exe 1   1   C++StaticClass

Can anyone point me in the right direction on how to fix my problem.

You need to initialize static variable in cpp file. Add following line in testClass.cpp file

std::vector<int> TestClass::Numbers;

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