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

I have a small class called Stuff in which I want to store things. These things are int type lists. In all my code, in any classes that I use, I want to have access to 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 external elements C: \ Stuff \ Projects \ CSandbox \ Debug \ CSandbox.exe CSandbox

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

+6
c ++ static
source share
5 answers

Mentioning a static member in a class declaration is only a declaration. You must include one static member definition for the linker in order to properly connect everything. Typically, in your Stuff.cpp file Stuff.cpp you should include the following:

 #include "Stuff.h" list<int> Stuff::things; 

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

+15
source share

Static data members must be defined outside of class declarations, like methods.

For example:

 class X { public: static int i; }; 

There should also be the following:

 int X::i = 0; // definition outside class declaration 
+7
source share

Substance :: things are declared only, but not defined.

use:

 // Stuff.cpp #include "Stuff.h" std::list<int> Stuff::things; 

Added : It is also recommended to protect header files from multiple inclusion:

 // Stuff.h #ifndef STUFF_H_ #define STUFF_H_ #include <list> class Stuff { public: static std::list<int> things; }; #endif 
+4
source share

Just for your information, why this works is that in C ++ all global variables (including static global) are created before the start of the main function.

+2
source share

The static member must be declared in the class, but defined in the block (cpp file) where it really is.

The only exception is if the class is a template: in this case you need to define a member outside the class, but you must also specify it in the class declaration in the header file.

0
source share

All Articles