Search code examples
c++staticnamespaceslinkage

Declaring a static member with static linkage


I have a C++ class which declares a single static member. The entire class is contained in a header file and I'd rather avoid creating a .cpp file simply to contain the static member definition. I've been trying to use the static keyword (in the C sense) and anonymous namespaces, both of which should give a variable declared in a header file static linkage (asfaik) but neither approaches work, can anyone give me a solution to this problem?

struct ServiceType {} ;
struct Transport
{
    static ServiceType service ;
};

//error: definition of ‘Transport::service’ is not in namespace enclosing ‘Transport’
//namespace { ServiceType Transport::service ; }

//error: ‘static’ may not be used when defining a static data member
//static ServiceType Transport::service ;

Solution

  • If the goal is just to not have to create a .cpp file, the simplest solution would probably be to wrap the static data member in an inline static member function. In other words, something like:

    struct Transport
    {
        static ServiceType& service()
        {
            static ServiceType theData;
            return theData;
        }
    };
    

    Of course, you'll have to use the syntax service(), rather than just service, to access it.