"Undefined reference to"-error / static member var in C++/Qt -


first of all, i'm not familiar c++/qt, tried it, in c#... have problems pointers..

the story: use qserialport read , write on serial 232 port. of course, there should 1 instance, otherwise there access errors. idea define static member variable hold object.

the problem: error "undefined reference 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 on...     }     return obj; } 

in header file, declaring serialmanager::obj in header file.

in implementation file, defining obj, notserialmanager::obj.

the fix change

qserialport *obj = new qserialport(); 

to

qserialport *serialmanager::obj = new qserialport(); 

you may find want initialise nullptr, , construct on demand when need (that might solve problems dependencies, and/or improve program start times, if have many static objects construct).

if want ever construct single object, make pointer (but not pointed-to object) constant:

private:     static qserialport *const obj; 

that can safeguard against accidentally assigning again (but can make hard substitute different object unit tests).


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -