C++: Undefined reference to instance in Singleton class

aheld picture aheld · Jan 27, 2010 · Viewed 13.5k times · Source

I'm currently trying to implement a factory as a singleton. I practically used the textbook example of the Singleton pattern. Here's the .h file:

namespace oxygen{

class ImpFactory{

public:
    static boost::shared_ptr<ImpFactory> GetInstance();

private:
    static boost::shared_ptr<ImpFactory> mInstance;
};

and here's the .cpp file:

#include "impfactory.h"

using namespace oxygen;
using namespace boost;

shared_ptr<ImpFactory> ImpFactory::GetInstance(){
    if (mInstance.get() == 0)
        mInstance = shared_ptr<ImpFactory>(new ImpFactory());
    return mInstance;
}

The code compiles, but I get a linker error:

../../lib/oxygen/liboxygen.so.3.2.4: undefined reference to `oxygen::ImpFactory::mInstance'

This currently has three students stumped. Any ideas?

Answer

Eli Bendersky picture Eli Bendersky · Jan 27, 2010

You must define the static instance, not just declare it. The definition creates the actual object you refer to.

In your cpp file, add the line:

boost::shared_ptr<ImpFactory> ImpFactory::mInstance;