Unresolved external symbol on static class members

Daniel picture Daniel · Oct 12, 2008 · Viewed 130.1k times · Source

Very simply put:

I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions.

Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class' constructor, I am getting an "unresolved external symbol" error at compilation.

class test 
{
public:
    static unsigned char X;
    static unsigned char Y;

    ...

    test();
};

test::test() 
{
    X = 1;
    Y = 2;
}

I'm new to C++ so go easy on me. Why can't I do this?

Answer

Colin Jensen picture Colin Jensen · Oct 12, 2008

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)