Page 1 of 1

Static data member giving undefined reference errors.

Posted: Sat Sep 13, 2014 10:05 pm
by goku420
I am using the constructor/destructor code from Trion. Constructors are working, however when I attempt to use a static data member, it is giving me an undefined reference error. I don't think it's covered in the C++ wiki page. Note that I use constexpr so that I can use the array in an enum class and initialize it inside the class. However, the error persists if I don't use constexpr and initialize the elements manually.

Terminal.hpp

Code: Select all

class Terminal
{
	constexpr static uint32_t col_map[16] = {
		0x000000, 0x0000AA, 0x00AA00, 0x00AAAA,
		0xAA0000, 0xAA00AA, 0xAA5500, 0xAAAAAA,
		0x555555, 0x5555FF, 0x55FF55, 0x55FFFF,
		0xFF5555, 0xFF55FF, 0xFFFF55, 0xFFFFFF
	};
	
	enum class Color : uint32_t
	{
		Black = col_map[0],
		White = col_map[15]
	};
        // ...
};

static Terminal terminal;
Terminal.cpp

Code: Select all

void Terminal::drawcolormap()
{
// ...
     putpixel(n + i * 50, m + j * 40, col_map[col]);
// ...
Is there something extra that I have to do for static data members?

Notes:
  • I have tried to reproduce the undefined reference error in a test program using a regular compiler unsuccessfully.
  • Don't pay attention to "static Terminal terminal;" it seems unrelated to the error.

Re: Static data member giving undefined reference errors.

Posted: Sat Sep 13, 2014 10:37 pm
by xenos
You will need something like this in Terminal.cpp (either with or without constexpr, I'm not sure right now):

Code: Select all

constexpr uint32_t Terminal::col_map[16];

Re: Static data member giving undefined reference errors.

Posted: Sat Sep 13, 2014 10:41 pm
by goku420
XenOS wrote:You will need something like this in Terminal.cpp (either with or without constexpr, I'm not sure right now):

Code: Select all

constexpr uint32_t Terminal::col_map[16];
Thank you, that did it. Can you explain why?

Edit: Nevermind, I see now that it has to be defined outside the class as well as initialized inside the class.

Re: Static data member giving undefined reference errors.

Posted: Sun Sep 14, 2014 10:45 am
by xenos
Basically, the declaration of the static data member does not reserve any space for it in any object file. For this to happen you need to define it in exactly one source file, so that it will be included in the corresponding object file and can be found by the linker.