Error: undefined reference to 'vtable for Widget'
-
Hi,
How to solve the error
error: undefined reference to 'vtable for Widget'
in the example:#include <QApplication> #include <QWidget> #include <QTimer> #include <QDebug> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = nullptr) : QWidget(parent) { connect(&m_timer, &QTimer::timeout, this, &Widget::printMessage); } private slots: void printMessage() { qDebug() << "timer"; } private: QTimer m_timer; }; int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
-
@8Observer8
If you added theQ_OBJECT
macro at some point, I would advise clearing out the debug/release directory and trying a complete rebuild. Does that solve it?The other possibility is that you need a
virtual ~Widget() { }
, at one point I thought that was required forQObject
s but I don't actually think you have to have it now.... -
you're trying to create a QObject based class inside main.cpp
that's possible, but not intended.
Like @JonB said, definitely add the Q_OBJECT macro,
then explicitly include the moc file inside your main
#include "main.moc"
AFTER the class declaration
-
Clear/Rebuild - does not work.
Clear/Run qmake/Rebuild/ -does not wok.
Closing QtCreater and deleting the "build..." folder - does not work.
This error accrues on these lines:
class Widget : public QWidget
Widget(QWidget *parent = nullptr) : QWidget(parent) {
-
@J-Hilk said in Error: undefined reference to 'vtable for Widget':
then explicitly include the moc file inside your main
Error:
main.cpp:22: error: main.moc: No such file or directory #include "main.moc" ^~~~~~~~~~
-
class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = nullptr) : QWidget(parent) { connect(&m_timer, &QTimer::timeout, this, &Widget::printMessage); m_timer.start(100); } private slots: void printMessage() { qDebug() << "timer"; } private: QTimer m_timer; }; #include "main.moc" int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
explicitly execute qmake, as the moc file does not yet exists,
than run normal build -
RMB on the project > "Run qmake" > but I see
error: main.moc: No such file or directory #include "main.moc"
-
@8Observer8 QtCreator is not updated (like I said its not the normal way to do this),
if you executed qmake, simply build the project -
Yes, it works! Thank you very much!
#include <QApplication> #include <QWidget> #include <QTimer> #include <QDebug> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = nullptr) : QWidget(parent) { connect(&m_timer, &QTimer::timeout, this, &Widget::printMessage); m_timer.start(1000); } private slots: void printMessage() { qDebug() << "timer"; } private: QTimer m_timer; }; #include "main.moc" int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }