Home > OS >  LNK2005 Error When Implementing static Fields In a Struct
LNK2005 Error When Implementing static Fields In a Struct

Time:01-29

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?

CodePudding user response:

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
  • Related