c++ static class variable without cpp file

c++, static-members

Solution

Use inline function (free-standing or member):

inline unsigned &sNextID()
{
    static unsigned data = 0;
    return data;
}

Or class template (defenition of it's statics can be in header file):

template<typename tag>
struct Foo
{
    static unsigned sNextID;
};

template<typename tag>
unsigned Foo<tag>::sNextID=0;

Update: In C++17 `inline` variables are available:

struct Foo
{
    static inline unsigned sNextID;
};

Problem

I have a simple class for storing sensor data which can be summarized as ``` class Data { public: Data(){timestamp = Time::now(); id = sNextID++; data = 0; type = DATA_TYPE_UNKNOWN;} double data; Time timestamp; DataType type; private: static unsigned int sNextID; }; ``` I have a header file that declares a bunch of similar data classes. Given the simplicity of the classes there is no need for an implementation cpp file. The problem is, without an implementation file how do I initialize sNextID? I read somewhere that it defaults to 0 which would be fine, although relying on that seems a bit hackish. More importantly, though, without initializing it somewhere the linker complains of an undefined reference.

Original source

Related problems