Reputation: 188
I was implementing a singleton class for my game but every time I try to compile it, it gives a compilation error. The code is as follows :
//Singleton.h
#pragma once
class Singleton{
public:
static Singleton* Instance();
private:
Singleton(){};
static Singleton* m_instance;
};
Singleton* SingletonInstance = Singleton::Instance();
Singleton.cpp
//Singleton.cpp
#include "Untitled1.h"
Singleton* m_instance = nullptr;
Singleton* Singleton::Instance(){
if(m_instance == nullptr){
m_instance = new Singleton;
}
return m_instance;
}
I am getting the following errors:
||=== Build: Debug in df (compiler: GNU GCC Compiler) ===| obj\Debug\Untitled1.o||In function `ZN9Singleton8InstanceEv':| C:\Users\Samsung R519\Desktop\Untitled1.cpp|7|multiple definition of `SingletonInstance'| obj\Debug\main.o:C:\Users\Samsung R519\Desktop\main.cpp|4|first defined here| obj\Debug\Untitled1.o:Untitled1.cpp|| undefined reference to `Singleton::m_instance'| obj\Debug\Untitled1.o:Untitled1.cpp|| undefined reference to `Singleton::m_instance'| ||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 10 second(s)) ===|
What am I doing wrong?
Upvotes: 0
Views: 1259
Reputation: 41840
I suggest you to use the Scott Meyers singleton. I will avoid any error related to order of initialisation and any memory management error related to the singleton.
Here's how you implement it:
struct Singleton {
static Singleton& instance() {
static Singleton myInstance;
return myInstance;
}
};
If you want to return a pointer instead of a reference, this is equally fine.
Upvotes: 1
Reputation: 23041
There are two problems with your code.
Singleton* SingletonInstance = Singleton::Instance();
You shouldn't put the definition in header file. Instead, you should declare SingletonInstance
in the header and define it in .cpp file. In fact, there's no need to have this global variable. You can always call Singleton::Instance()
to get the singleton.
m_instance
is a member of Singleton
, so you should define it with the class name: Singleton::m_instance
The solution:
// xxx.h
// other code...
extern Singleton* SingletonInstance; // declaration
// xxx.cpp
// other code...
Singleton* Singleton::m_instance = nullptr; // specify the class name
Singleton* SingletonInstance = Singleton::Instance(); // definition
Upvotes: 3
Reputation: 4961
class Singleton{
....
static Singleton* m_instance;
}
and
Singleton* m_instance = nullptr;
Even though have the same name, they are different pointers because they have different scopes: the first one is a declaration of a class member and the second one is both a declaration and a definition of a pointer in the global namespace.
So, what you are looking for is the definition of the class member pointer, which is:
Singleton* Singleton::m_instance = nullptr;
Upvotes: 1
Reputation: 92381
In the .cpp file you are defining a new m_instance
that is not a member.
Please try
Singleton* Singleton::m_instance = nullptr;
Upvotes: 3