Reputation: 483
First of all, I'm not really familiar with C++/Qt
, so I tried it, as i would do it in C#
... I also have some problems with pointers..
The story: I use the QSerialPort
to read and write on a serial 232 port. Of course, there should be only one instance, otherwise there would be access errors. So my idea was to define a static member variable to hold the object.
The problem: I always get the error "undefined reference to SerialManager::obj
"
The source code:
serialmanager.h
#include <QSerialPort>
class SerialManager
{
public:
static QSerialPort* getObj();
private:
static QSerialPort* obj;
}
serialmanager.cpp
#include "serialmanager.h"
QSerialPort *obj = new QSerialPort();
QSerialPort* SerialManager::getObj()
{
if(!obj->isOpen())
{
obj->setPortName("/dev/ttyO1"); //error line
obj->setBaudRate(QSerialPort::Baud57600);
//and so on...
}
return obj;
}
Upvotes: 0
Views: 103
Reputation: 30709
In the header file, you are declaring SerialManager::obj
in the header file.
In your implementation file, you are defining obj
, notSerialManager::obj
.
The fix is to change
QSerialPort *obj = new QSerialPort();
to
QSerialPort *SerialManager::obj = new QSerialPort();
You may find you want to initialise it to nullptr
, and construct on demand when you need it (that might solve problems with dependencies, and/or improve program start times, if you have many static objects to construct).
If you really want to only ever construct a single object, you could also make the pointer (but not the pointed-to object) constant:
private:
static QSerialPort *const obj;
That can safeguard against accidentally assigning again (but can make it hard to substitute a different object for your unit tests).
Upvotes: 2
Reputation: 8356
You are missing the class's name, fix it by changing
QSerialPort *obj = new QSerialPort();
into
QSerialPort *SerialManager::obj = new QSerialPort();
Upvotes: 1