我有一个相对简单的Qt 5.0项目,使用的是CMake 2.8.9:
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:
->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创建的 .ui 文件(MainWindow.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,但我从来没有记得在编译一个微不足道的示例时遇到过这么多麻烦。我做错了什么?
编辑:这是用于链接所有内容的命令:
/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
add_library
函数中添加头文件了。谢谢你。 - Saeed Masoomi