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_ */
CodePudding user response:
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