C++11: undefined reference to static class member

Hello,

(preview not working for me, apologies if this comes out misformatted)

What is wrong with this?

// test.h
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
30
#ifndef TEST_H 
#define TEST_H

void a (int, int);
void b (int, int);
void c (int, int);

class TheClass
{
public:
	typedef void (*fnct) (int, int);
	
protected:
	
	typedef struct {
		int id;
		fnct fn;
	} idfn_tuple;
	
	static constexpr idfn_tuple list[] = {
		{ .id = 0, .fn = a },
		{ .id = 1, .fn = b },
		{ .id = 2, .fn = c }
	};
	
	static const idfn_tuple * find ( int id );
	
};

#endif // TEST_H 



// test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "test.h"

void a (int, int) { /*Do nothing*/ }

void b (int, int) { /*Do nothing*/ }

void c (int, int) { /*Do nothing*/ }

const TheClass::idfn_tuple * TheClass::find ( int id )
{
	return &list[id];
}


int main()
{
	return 0;
}

// end of test.cpp

Output:
1
2
3
4
> g++ test.cpp 
/usr/lib64/gcc/x86_64-suse-linux/9/../../../../x86_64-suse-linux/bin/ld: /tmp/cc5Dz4ZB.o: in function `TheClass::find(int)':
test.cpp:(.text+0x3a): undefined reference to `TheClass::list'
collect2: error: ld returned 1 exit status



Thank you.


Last edited on
Defining the static variable from within the class like that I think it only allowed starting C++14 or C++17.

Also, if you enable -Wpedanic, you'll get this warning
main.cpp:21:5: warning: C++ designated initializers only available with -std=c++2a or -std=gnu++2a [-Wpedantic]
   { .id = 0, .fn = a },
(GCC itself has had the extension built-in for a while)

So, in C++11, the static variable needs to be defined outside of the class definition itself.

Edit: Sorry, poor wording, I'm not sure what the correct wording is, but basically you need to do this:

1
2
3
4
5
6
7
8
9
10
11
class TheClass 
{
	static constexpr idfn_tuple list[] = {
		{ .id = 0, .fn = a },
		{ .id = 1, .fn = b },
		{ .id = 2, .fn = c }
	};
};

constexpr TheClass::idfn_tuple TheClass::list[];
Last edited on
Hello Ganado,

Thank you for your reply. Indeed, shortly after posting we came to the same conclusion with a colleague of mine.

The really baffling thing is that the code WAS working until this morning, when we added an extra member at the end of the array. And we have been using g++11 all along. Mysteries of life.

We need to stay with c++11 so refactored the code. Thanks once again.
Topic archived. No new replies allowed.