-1

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?

  • 1
    Same way that you defined `Black`? I don't see the problem. – john Jan 29 '23 at 08:59
  • 1
    Except that you should move `Color::Black` out of the header file. and you should declare it `const`. – john Jan 29 '23 at 09:00
  • Another solution would be to initialize `Black` when you declare it in `Color`. – Ivan Venkov Jan 29 '23 at 09:06
  • 1
    Either move the definition of the static member variable (`...::Black = Color...`) to an implementation file or add the `inline` modifier. Personally I'd go with making the variable `constexpr` which implies `inline` (requires you to make the constructor `constexpr` as well). – fabian Jan 29 '23 at 09:08

1 Answers1

0

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
john
  • 85,011
  • 4
  • 57
  • 81