首页 文章

连接此Qt 5.0应用程序时,为什么会出现“未定义的引用vtable ...”错误?

提问于
浏览
10

我有一个使用CMake 2.8.9的相对简单的Qt 5.0项目:

的CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.9)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
project(hello-world)

find_package(Qt5Widgets REQUIRED)
qt5_wrap_ui(hello-world_UI MainWindow.ui)

add_executable(hello-world MainWindow.cpp main.cpp ${hello-world_UI})
qt5_use_modules(hello-world Widgets)

MainWindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

    public:

        MainWindow();
        virtual ~MainWindow();

    private:

        Ui::MainWindow * const ui;
};

#endif // CMAINWINDOW_H

MainWindow.cpp:

#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow()
    : ui(new Ui::MainWindow)
{
}

MainWindow::~MainWindow()
{
    delete ui;
}

main.cpp中:

#include <QApplication>
#include "MainWindow.h"

int main(int argc, char * argv[])
{
    QApplication app(argc, argv);

    MainWindow win;
    win.show();

    return app.exec();
}

该项目还包括使用Qt Creator 2.6.1(MainWindow.ui)创建的 .ui 文件 .

当我尝试在Linux上使用 g++ 构建文件时,收到以下错误:

CMakeFiles/hello-world.dir/MainWindow.cpp.o: In function `MainWindow::MainWindow()':
MainWindow.cpp:(.text+0x3b): undefined reference to `vtable for MainWindow'
MainWindow.cpp:(.text+0x4d): undefined reference to `vtable for MainWindow'
CMakeFiles/hello-world.dir/MainWindow.cpp.o: In function `MainWindow::~MainWindow()':
MainWindow.cpp:(.text+0xaf): undefined reference to `vtable for MainWindow'
MainWindow.cpp:(.text+0xc1): undefined reference to `vtable for MainWindow'
collect2: error: ld returned 1 exit status

什么可能导致这种错误?我最近从 qmake 切换到CMake,我从来没有记得遇到这个麻烦的例子来编译 . 我究竟做错了什么?


Edit: 这是用于链接所有内容的命令:

/usr/bin/c++ CMakeFiles/hello-world.dir/MainWindow.cpp.o
CMakeFiles/hello-world.dir/main.cpp.o -o hello-world -rdynamic
/usr/local/Qt-5.0.0/lib/libQt5Widgets.so.5.0.0
/usr/local/Qt-5.0.0/lib/libQt5Gui.so.5.0.0
/usr/local/Qt-5.0.0/lib/libQt5Core.so.5.0.0 
-Wl,-rpath,/usr/local/Qt-5.0.0/lib

2 回答

  • 19

    事实证明我忘记了:

    set(CMAKE_AUTOMOC ON)
    

    位于CMakeLists.txt文件的顶部 .

  • 3

    使用此处发布的所有提示,我在这方面挣扎了很长时间:

    http://doc.qt.io/qt-5/cmake-manual.html

    和这里

    https://www.kdab.com/using-cmake-with-qt-5/

    我必须做的是按正确的顺序指定事物 . 例如,以下是我的CMakeLists.txt的顶部 . 请注意,两个CMAKE集指令在add_executable之前 . 一旦我这样做,我能够链接没有未定义的符号和vtable引用 . 我只是觉得我会发布这个是为了别人的利益 .

    cmake_minimum_required (VERSION 2.8)
    
    set (CMAKE_AUTOMOC ON)
    set (CMAKE_INCLUDE_CURRENT_DIR ON)
    add_executable(FHSpectrumSensor wideband_seq_spectrum_sensor.cpp sensor.cpp   gui.cpp ${gui_SRC})
    

    稍后在CMakeLists.txt中我有以下内容:

    find_package(Qt5Widgets REQUIRED)
     find_package(Qt5Charts REQUIRED)
     find_package(Qt5Core REQUIRED)
    
     qt5_use_modules(FHSpectrumSensor Widgets Charts)
     qt5_wrap_cpp(gui_SRC gui.h gui.cpp)
    

    这就是诀窍 .

相关问题