darkpsychic darkpsychic - 5 months ago 24
C++ Question

Error in Singleton

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 :

#pragma once

class Singleton{
static Singleton* Instance();


static Singleton* m_instance;

Singleton* SingletonInstance = Singleton::Instance();


#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?


There are two problems with your code.

  1. 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.

  2. 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