Search code examples
c++structstaticfieldlnk2005

LNK2005 Error When Implementing static Fields In a Struct


I get LNK2005 "public: static struct Color Color::Black already defined in ***.obj

Color.h file contents:

#pragma once

struct Color
{
    Color(float r, float g, float b) : R{ r }, G{ g }, B{ b }, A{ 1.0f }{}

    float R;
    float G;
    float B;
    float A;

    static Color Black;
};

Color Color::Black = Color(0.0f, 0.0f, 0.0f);

What would be the correct way of implementing a bunch of default colors like black, white, red, green, etc?


Solution

  • I would go for this

    // header file
    #pragma once
    
    struct Color
    {
        Color(float r, float g, float b) : R{ r }, G{ g }, B{ b }, A{ 1.0f }{}
    
        float R;
        float G;
        float B;
        float A;
    
        static const Color Black;
        static const Color Red;
        // etc
    };
    
    // cpp file
    
    const Color Color::Black = Color(0.0f, 0.0f, 0.0f);
    const Color Color::Red = Color(1.0f, 0.0f, 0.0f);
    // etc