0

The Qt projects on QtCreator usually keep main.cpp separated from QtMainWindow derived classes.

I tried to move it to main.cpp but got stuck:

myapp.pro

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TEMPLATE = app

CONFIG += c++11

SOURCES += main.cpp

main.cpp

#include <QApplication>
#include <QMainWindow>

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    MainWindow(QWidget *parent=0) : QMainWindow(parent) { }
    virtual ~MainWindow() override {}
};

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    MainWindow w;
    return a.exec();
}

Then and got:

Undefined symbols for architecture x86_64:
  "vtable for MainWindow", referenced from:
      _main in main.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [demo1.app/Contents/MacOS/demo1] Error 1

Having a difficult time trying to find the mistake I made. Any comments?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136

3 Answers3

3

It is a moc problem. When subclassing a QObject that uses the Q_OBJECT macro, you need to put it in its own file. You can't compile it with your main.cpp.

JimmyG
  • 131
  • 1
  • 9
1

The meta-object compiler (moc) only processes header files (.h). The moc documentation mentions this briefly. I'm guessing it's because the declaration of a QObject subclass alone is sufficient to generate the signals/slots code; i.e. the implementation that would normally be in the .cpp file is unnecessary for moc to do its thing.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Carlton
  • 4,217
  • 2
  • 24
  • 40
0

In most cases this is because you did not declare the destructor:

virtual ~MainWindow() override {}

That's the one function that will trigger the compiler code necessary to create the vtable.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156