Important: Please read the Qt Code of Conduct -

Implementation Singleton problem

  • Hi,
    I wrote class SMessenger which is a singleton but during compilation i get error:
    undefined reference to 'SMessenger::instance_'

    This is my code

    class SMessenger : public QMqttClient
        static SMessenger* instance(){
            if(!instance_) instance_ = new SMessenger();
            assert(instance_ != NULL);
            return instance_;
    public slots:
        void sendMsgToDevice(QString topic, bool state);
        SMessenger(QObject *parent = nullptr);
        SMessenger(SMessenger const&);
        SMessenger& operator=(SMessenger const&);
        static SMessenger* instance_;
        QMqttClient *m_mqttClient;
    private slots:
        void slotErrorChanged(const QMqttClient::ClientError e);
        void slotStateChanged();
        void slotDisconnected();
        void slotConnected();
        void signalNewParamsFromGreenhouse(Current_parameters parameters);

    The problem is in the method instance()

  • Moderators

    You're missing a definition of your static variable. Put that in your .cpp file:

    SMessenger* SMessenger::instance_ = nullptr;

    Btw. don't forget to delete your singleton before your application object is destroyed. No QObject should live longer than that. One way to do it is to connect QApplication::aboutToQuit signal to your singleton's deleteLater slot when you're creating it.

    Btw.2 Don't use NULL. It's an old C style macro. If you need to be that explicit use nullptr or you could just assert(instance_).

Log in to reply