g++.exe says undefined reference to static member variable

Hello, g++ doesn't seem to like this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

class object
{
public:
    object()
    {
        obj_count += 1;
        std::cout << "Object count: " << obj_count << '\n';
    }
	
	int val;
    static int obj_count;
};

void Func(object o)
{
    std::cout << "Func called.\n";
}

int main()
{
    object o;
    Func(o);

    return 0;
}


Not one of my better codes, it's just to test some stuff.

EDIT:
This code works:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 #include <iostream>

class object
{
public:
    object()
    {
        obj_count += 1;
        std::cout << "Object count: " << obj_count << '\n';
    }
    
    int val = 0;
    static int obj_count;
};

int object::obj_count = 0;

void Func(object o)
{
    std::cout << "Func called.\n";
}

int main()
{
    object o;
    Func(o);

    return 0;
}


Weird what one line can do to a code...
Last edited on
Define the static member (in some .cpp file)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

class object
{
public:
    object()
    {
        obj_count += 1;
        std::cout << "Object count: " << obj_count << '\n';
    }
	
	int val;
    static int obj_count;
};

void Func(object)
{
    std::cout << "Func called.\n";
}

int main()
{
    object o;
    Func(o);

    return 0;
}

int object::obj_count = 0 ; // **** define it **** 


http://coliru.stacked-crooked.com/a/a0a234b51157d2ea
Thanks! :P
Topic archived. No new replies allowed.