4

I've just started programming in Qt framework. Following is a very simple program:

#include <QtCore/QCoreApplication> #include <QDebug> class MyClass : public QObject { Q_OBJECT public: MyClass() {} }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyClass *c = new MyClass(); return a.exec(); } 

But I receive following error when I try to compile & run it:
In function MyClass:
undefined reference to vtable for MyClass
But when I remove the QObject macro everything works fine. Please note that the class is defined in the same file as the main function.
I'm using Qt version 4.7, running on Win 7.
What is causing this issue?

Update: I get the same error when I define my class in a separate header file. mytimer.h:

#ifndef MYTIMER_H #define MYTIMER_H #include <QtCore> class MyTimer : public QObject { Q_OBJECT public: QTimer *timer; MyTimer(); public slots: void DisplayMessage(); }; #endif // MYTIMER_H 

mytimer.cpp:

#include "mytimer.h" #include <QtCore> MyTimer::MyTimer() { timer = new QTimer(); connect(timer,SIGNAL(timeout()),this,SLOT(DisplayMessage())); timer->start(1000); } void MyTimer::DisplayMessage() { qDebug() << "timed out"; } 

And this is the main.cpp:

#include <QtCore/QCoreApplication> #include <QDebug> #include "mytimer.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyTimer *mt = new MyTimer(); return a.exec(); } 
8
  • Show the command(s) you are using to compile the code please. Commented Mar 29, 2012 at 16:41
  • Qt2.7 is quite old... have you tried a newer version? 4.8 is the latest, I think. Commented Mar 29, 2012 at 16:42
  • @tmpearce It was a mistake, it's 4.7.4 Commented Mar 29, 2012 at 16:46
  • Try calling the QObject constructor: MyTimer::MyTimer : QObject(NULL) {...} Commented Mar 29, 2012 at 16:55
  • Can you paste your build process, I suspect that that is where the issue lies. Commented Mar 29, 2012 at 16:57

3 Answers 3

4

You need to compile it using qmake, which is going to create mock methods for your custom QObject class. See here about more on generating moc files.

Since your example doesn't contain header files, it is not parsed, and no moc files are generated. You need to declare MyClass in a separate header file, and run moc generation tool.

Sign up to request clarification or add additional context in comments.

1 Comment

while this may be helpful, you don't need to compile with qmake; you do have to configure things properly though, no matter which compile/build system you use.
1

When you are using QT Creator you should cleanup up your project and execute qmake, in the build menu.

Comments

1

Whenever u apply some changes first clean your project, then run qmake, and the finally build your project...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.