Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Undefined reference to instance in Singleton class

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?

like image 486
aheld Avatar asked Jan 27 '10 08:01

aheld


2 Answers

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;
like image 118
Eli Bendersky Avatar answered Oct 05 '22 06:10

Eli Bendersky


You need a definition for your static member in a cpp file.

boost::shared_ptr<ImpFactory> ImpFactory::mInstance;
like image 31
Nikola Smiljanić Avatar answered Oct 05 '22 07:10

Nikola Smiljanić