0

I am trying to use Singleton pattern in an embedded project, but I can't compile the project. The class, now, is very simple and I don't understand the problem.

The error is (48, in my code is the last line of instance function):

RadioWrapper.h:48: undefined reference to `RadioWrapper::mInstance'

Any ideas?

#define RADIOWRAPPER_H_

class RadioWrapper
{
protected:
    RadioWrapper() {};
    ~RadioWrapper() { mInstance = NULL;}

public:

    static RadioWrapper* instance (void)
    {
        if (!mInstance)
        {
            mInstance = new RadioWrapper();
            return mInstance;
        }
        else
        {
            return mInstance;
        }
    }

    void setRx (void);

private:
    static RadioWrapper* mInstance;

};

#endif /* RADIOWRAPPER_H_ */
the busybee
  • 10,755
  • 3
  • 13
  • 30
warcomeb
  • 13
  • 5
  • Works for me. Please provide a [mre] for the next to try your code. -- Which compiler do you use, how do you compile (command line)? – the busybee Apr 12 '22 at 09:03
  • If you have a compiler in your environment, that does support c++11 or more modern, then search for "Meyers singleton", a safe and easy pattern. – kaba Apr 12 '22 at 09:08
  • @kaba I am using g++14 on microcontroller. I will search Meyers singleton. Thanks – warcomeb Apr 12 '22 at 09:25

1 Answers1

0

A static member of a class, like static RadioWrapper* mInstance, has to be defined (what you have in the H file is a declaration only).

You need to add:

/*static*/ RadioWrapper::mInstance = nullptr;

(the /*static*/ prefix is for documentation only).

This should be added in a CPP file, not H file (otherwise if the H file is included more than once, you'll have multiple definitions.)

If you are using C++ 17, you can use an inline variable that can be defined and initialized in the H file. See the 2nd answer here: How to initialize static members in the header

wohlstad
  • 12,661
  • 10
  • 26
  • 39