Differences

This shows you the differences between two versions of the page.

Link to this comparison view

tutorials:qt:qt_undefined_reference_to_vtable [2019/10/04 14:41] (current)
alanzheng created
Line 1: Line 1:
 +Sometimes you will see the error message: "​undefined reference to `vtable for MainWindow'"​ when developing Qt program, it mostly because you dont use Qt's moc program to generate the .cpp file which related to the .h file that included Q_OBJECT macro.
  
 +Suppose you have MainWindow.h
 +<​code>​
 +#ifndef MainWindow_h__
 +#define MainWindow_h__
 +
 +#include <​QMainWindow>​
 +#include <​QMdiArea>​
 +
 +class MainWindow : public QMainWindow
 +{
 +  Q_OBJECT
 +
 +public:
 +  MainWindow( QWidget* parent = 0, Qt::​WindowFlags flags = 0 );
 +  ~MainWindow();​
 +
 +private slots:
 +  void onCreateView();​
 +
 +private:
 +  QMdiArea* mdiArea_;
 +};
 +
 +#endif
 +</​code>​
 +
 +and MainWindow.cpp:​
 +<​code>​
 +#include "​MainWindow.h"​
 +#include <​QDebug>​
 +#include <​QMdiSubWindow>​
 +#include <​QMenuBar>​
 +
 +MainWindow::​MainWindow( QWidget* parent, Qt::​WindowFlags flags )
 +  : QMainWindow( parent, flags ),
 +    mdiArea_( new QMdiArea( this ) )
 +{
 +  QMenuBar* menuBar = this->​menuBar();​
 +  QMenu* menu = menuBar->​addMenu( "​Test"​ );
 +  menu->​addAction( "​Create view", this, SLOT( onCreateView() ) );
 +  this->​setCentralWidget( mdiArea_ );
 +}
 +
 +MainWindow::​~MainWindow()
 +{
 +}
 +
 +void MainWindow::​onCreateView()
 +{
 +}
 +</​code>​
 +
 +Everything looks fine for normal c++ code, but when you compiled the MainWindow.cpp,​ you will get the "​undefined reference to `vtable for MainWindow'"​ link error, since Qt doesn'​t like that.
 +
 +To fix this error, you just need use Qt' moc command to generate related cpp file likes below:
 +<​code>​
 +moc MainWindow.h -o moc_MainWindow.cpp
 +</​code>​
 +
 +After it, to compile MainWindow.cpp and moc_MainWindow.cpp,​ everything will really fine.
 +Hope my post can save your life :-) Enjoy programming! ​