linker error by static member

Hello there, can someone say why I get a linker error by the subjacent example?

X.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef X_H
#define X_H

#include <vector>
struct X
{
    // static member
    static std::vector<X> * m_container;
    
    // static method   
    static void set_container( std::vector<X>& );
};
#endif 


X.cpp:
1
2
3
4
5
6
#include "X.h"

void X::set_container( std::vector<X>& c)
{
    m_container = &c;
}


main.cpp:
1
2
3
4
5
6
#include "X.h"

int main()
{
    std::vector<X> vec(1);
}

I compile and link with 'c++ main.cpp X.cpp' and get this linker error:
[text]
X-36e580.o: In function `X::set_container(std::vector<X, std::allocator<X> >&)':
X.cpp:(.text+0x10): undefined reference to `X::m_container'
[/text]
Static members must be defined in a source file. Change your 'X.cpp' file to look like this:
1
2
3
4
5
6
7
8
#include "X.h"

std::vector<X> X::m_container = nullptr;

void X::set_container(std::vector<X>& c)
{
m_container = &c;
}
Topic archived. No new replies allowed.