Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't my C++ program link when my class has static members?

Tags:

c++

static

I have a little class called Stuff that I want to store things in. These things are a list of type int. Throughout my code in whatever classes I use I want to be able to access these things inside the Stuff class.

Main.cpp:

#include "Stuff.h"

int main()
{
    Stuff::things.push_back(123);
    return 0;
}

Stuff.h:

#include <list>

class Stuff
{
public:
    static list<int> things;
};

but I get some build errors with this code:

error LNK2001: unresolved external symbol "public: static class std::list<int,class std::allocator<int> > Stuff::things" (?things@Stuff@@2V?$list@HV?$allocator@H@std@@@std@@A) Main.obj CSandbox

fatal error LNK1120: 1 unresolved externals C:\Stuff\Projects\CSandbox\Debug\CSandbox.exe CSandbox

I am a C# guy, and I am trying to learn C++ for a side project. I think that I don't understand how C++ treats static members. So please explain what I have got wrong here.

like image 450
Mr Bell Avatar asked Dec 29 '09 21:12

Mr Bell


2 Answers

Mentioning a static member in a class declaration is a declaration only. You must include one definition of the static member for the linker to hook everything up properly. Normally you would include something like the following in a Stuff.cpp file:

#include "Stuff.h"

list<int> Stuff::things;

Be sure to include Stuff.cpp in your program along with Main.cpp.

like image 55
Greg Hewgill Avatar answered Nov 07 '22 10:11

Greg Hewgill


Static data members have to be defined outside class declarations, much like methods.

For example:

class X {
    public:
        static int i;
};

Must also have the following:

int X::i = 0; // definition outside class declaration
like image 22
KingRadical Avatar answered Nov 07 '22 11:11

KingRadical