Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking static singleton class

when i try to link a SIngleton class a get

sources/singleton.cpp:8:41: error: no se puede declarar que la función miembro ‘static myspace::Singleton& myspace::Singleton::Instance()’ tenga enlace estático [-fpermissive]
sources/director.cpp:19:35: error: no se puede declarar que la función miembro ‘static void myspace::Singleton::Destroy()’ tenga enlace estático [-fpermissive]
myspace: *** [objects/singleton.o] Error 1

the Singleton class:

#Singleton.h
#include <stdlib.h>

namespace myspace {

    class Singleton
    {
    public:
        static Singleton& Instance();
        virtual ~Singleton(){};
    private:
        static Singleton* instance;
        static void Destroy();
        Singleton(){};
        Singleton(const Singleton& d){}
    };
}

#Singleton.cpp
#include "../includes/Singleton.h"

namespace myspace {
    Singleton* Singleton::instance = 0;

    static Singleton& Singleton::Instance()
    {
        if(0 == instance) {
            instance = new Singleton();

            atexit(&Destroy);
        }

        return *instance;
    }

    static void Singleton::Destroy()
    {
        if (instance != 0) delete instance;
    }
}

i need some LDFLAGS to the linker?

like image 225
rkmax Avatar asked Jan 21 '26 13:01

rkmax


2 Answers

You can only declare methods static in the declarations, it's not allowed in the implementations. Just change your implementations to;

Singleton& Singleton::Instance()
{

and

void Singleton::Destroy()
{

and you should be fine.

like image 181
Joachim Isaksson Avatar answered Jan 23 '26 04:01

Joachim Isaksson


You need to remove static from the definitions in the cpp file: the compiler already knows the Singleton::Instance and Singleton::Destroy are static from their declarations. Everything else looks right.

like image 40
Sergey Kalinichenko Avatar answered Jan 23 '26 02:01

Sergey Kalinichenko