1

I have a pixel struct. I want to decalre static constants inside of it for colors like BLACK and WHITE. I am writing all of the in a header file which will be included in multiple cpp files.

struct Pixel
{
    typedef uint16_t quantum_t; 
    static const quantum_t MAX_QUANTUM = 0xffffL;
    static const quantum_t MIN_QUANTUM = 0;
    static const int QUANTUM_BITS = 16;

    quantum_t r, g, b;

    Pixel(quantum_t r_ = 0, quantum_t g_ = 0, quantum_t b_ = 0) :
        r(r_), g(g_), b(b_) { }

    template<typename T>
    static T clamp(T x)
    {
        return x > MAX_QUANTUM ? MAX_QUANTUM : (x < MIN_QUANTUM ? MIN_QUANTUM : x);
    }

    template<typename T>
    static Pixel clamp(T r, T g, T b)
    {
        return Pixel(clamp(r), clamp(g), clamp(b));
    }

    static const Pixel BLACK;
    static const Pixel WHITE;
};

const Pixel Pixel::BLACK(0, 0, 0);
const Pixel Pixel::WHITE(Pixel::MAX_QUANTUM, Pixel::MAX_QUANTUM, Pixel::MAX_QUANTUM);

Initially I tried to initialize the static BLACK and WHITE inside ofthe struct however I got an error from g++ about having an incomplete type. Once I declared the static variables outside of the struct the error went away and the code now compiles. This is a header only library and what I am wondering is will declaring the static variables like this cause compilation issues if it is included in multiple cpp files?

chasep255
  • 11,745
  • 8
  • 58
  • 115
  • Possible duplicate of [Defining static members in C++](http://stackoverflow.com/questions/3536372/defining-static-members-in-c) – Adam Nov 05 '15 at 01:55

1 Answers1

1

will declaring the static variables like this cause compilation issues if it is included in multiple cpp files?

No, because the C++ standard allows this particular usage and unless they are declared extern they will not be seen or collide with other instances of the same named variable in other translation units (i.e. cpp files).

GreatAndPowerfulOz
  • 1,767
  • 13
  • 19