I have written this Singleton demonstration program 'by the book', but it does not seem to be compiling. I am getting a linker error from the compiler concerning the static variable inside the singleton class that holds the single Singleton instance. What might be the reason?
#include <iostream>
#include "Singleton.h"
//using namespace std;
int main()
{
Singleton * sinObj1 = Singleton::Instance();
sinObj1 -> setInt (3);
Singleton * sinObj2 = Singleton::Instance();
std::cout << sinObj2 -> getInt() << std::endl;
return 0;
}
/*
* Singleton.h
*
* Created on: Feb 26, 2014
* Author: edwinrietmeijer
*/
#ifndef SINGLETON_H_
#define SINGLETON_H_
#include <iostream>
class Singleton {
public:
static Singleton* Instance();
void setInt( int );
int getInt();
void method();
private:
Singleton();
Singleton( const Singleton& );
Singleton& operator=( Singleton const& );
static Singleton* m_instance;
int anInt;
};
#endif /* SINGLETON_H_ */
/*
* Singleton.cpp
*
* Created on: Feb 26, 2014
* Author: edwinrietmeijer
*/
#include "Singleton.h"
Singleton* Singleton::Instance()
{
if ( !m_instance ) // Only allow one instance of class to be generated.
m_instance = new Singleton;
return m_instance;
}
void Singleton::method() {
std::cout << "Method" << std::endl;
}
void Singleton::setInt( int i ) {
anInt = i;
}
int Singleton::getInt() {
return anInt;
}
Singleton::Singleton() : anInt( 0 ){
// TODO Auto-generated constructor stub
}
Error:
Building target: SingletonTest
Invoking: MacOS X C++ Linker
g++ -o "SingletonTest" ./src/Singleton.o ./src/SingletonTest.o
Undefined symbols for architecture x86_64:
"Singleton::m_instance", referenced from:
Singleton::Instance() in Singleton.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [SingletonTest] Error 1