0

I created the simplest class for working with QTimer in my console application.

The compiler generates an error: Undefined reference to `vtable for Timer'. Whereind refers to the string with constructor: Timer() {}

I found many recommendations on this issue on this site, for example:

Undefined reference to vtable. Trying to compile a Qt project

Qt Linker Error: "undefined reference to vtable"

Q_OBJECT throwing 'undefined reference to vtable' error

All the answers boil down to clearing the project, then running QMake and rebuilding the project. Unfortunately, all this did not help me. I also tried to delete the "Debug" folder, and after doing the above actions - the result is the same.

I constantly and actively use the technique of signals and slots in real multi-file programs, and I have never encountered such problems.

Please share your ideas!

#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QObject>

class Timer : public QObject {
    Q_OBJECT

public:
    Timer() {}
    virtual ~Timer() {}

public slots:
    void someSlot();
};

void Timer::someSlot() {
    qDebug() << "someSlot()";
}

int main(int argc, char *argv[])
{
    QCoreApplication aa(argc, argv);

    QTimer *timer = new QTimer();
    Timer *myTimer = new Timer();

    QObject::connect(timer, SIGNAL(timeout()), myTimer, SLOT(someSlot()));
    timer->start(1500);

    return aa.exec();
}

//-----------------------
// pro-file

QT += core
QT -= gui

CONFIG += c++11 c++14

TARGET = test_for_all
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp
Konstantin
  • 25
  • 1
  • 5

2 Answers2

2

Since your Timer has only form of definition (no declaration in header) Qt moc tool is unable to detect Q_OBJECT macro and generate required implementation of slots, signals and meta data information.

To fix it you can do one of this:

  • create header with Timer declaration
  • pretend that your source code is also a header so this file is feed to mock tool. So just add in pro file:
HEADERS += main.cpp
Marek R
  • 27,988
  • 5
  • 42
  • 123
2

You have to create header file for your class and add it to your *.pro file properly since it was inherited from QObject.

Konstantin T.
  • 972
  • 6
  • 18
  • Yes, creating separate .h and .cpp files for a class is not difficult. After that, the code began to work. But I want to understand the following. Can I create a class directly in main.cpp before the main () function in a simple console application? Just adding the HEADERS + = main.cpp line to the .pro file did not work. – Konstantin May 15 '19 at 10:43
  • 1
    @Konstantin There is some trick. At the very end of `main.cpp` file add `#include "main.moc"`. Then rerun qmake and rebuild the project. It works for me, but I wouldn't recomend it :) – Konstantin T. May 15 '19 at 11:37