我在 CMake 项目中遇到了 Qt 元对象编译器的问题。我正在构建的共享库包含以下代码并使用 pimpl 习惯用法。调用 CMake 并编译后我得到
AUTOGEN:错误:~/tools/Project/gui/src/mainWindow.cpp:该文件包含 Q_OBJECT 宏,但不包含“mainWindow.moc”!gui/CMakeFiles/gui_automoc.dir/build.make:57: 目标'gui/CMakeFiles/gui_automoc' 的配方失败 make[2]: *** [gui/CMakeFiles/gui_automoc] 错误 1 CMakeFiles/Makefile2:234: 配方目标 'gui/CMakeFiles/gui_automoc.dir/all' 失败
我不明白我做错了什么,或者在我的项目中将 src 文件与 Q_OBJECT 宏合并的正确方法是什么。请帮忙=/
gui/include/gui/mainWindow.hpp
#include <QMainWindow>
#include <string>
class MainWindow : public QMainWindow {
class MainWindowImpl;
public:
MainWindow(QWidget* parent = nullptr);
private:
MainWindowImpl* pimpl_;
};
gui/src/mainWindow.cpp
#include "gui/mainWindow.hpp"
class MainWindow::MainWindowImpl : public QWidget{
Q_OBJECT
public:
explicit MainWindowImpl(MainWindow *parent);
private:
MainWindow &parent_;
};
MainWindow::MainWindowImpl::MainWindowImpl(MainWindow *parent)
: QWidget{parent}, parent_(*parent) {}
MainWindow::MainWindow(QWidget *parent) : QMainWindow{parent} {
pimpl_ = new MainWindowImpl{this};
setCentralWidget(pimpl_);
}
我像这样编译库:
cmake_minimum_required(VERSION 3.5.1 FATAL_ERROR)
project(gui)
QT5_WRAP_CPP(MOC_Files
include/gui/mainWindow.hpp
)
add_library(${PROJECT_NAME}
SHARED
src/mainWindow.cpp
${MOC_Files}
)
add_library(gui::gui ALIAS ${PROJECT_NAME})
target_include_directories(${PROJECT_NAME}
PUBLIC
${PROJECT_SOURCE_DIR}/include
)
set_target_properties(${PROJECT_NAME} PROPERTIES AUTOMOC TRUE)
target_link_libraries(${PROJECT_NAME}
PUBLIC
Qt5::Widgets
Qt5::Core
Qt5::Xml
Qt5::OpenGL
Qt5::Gui
)
install(TARGETS ${PROJECT_NAME} DESTINATION lib)
现在我想将此库链接到我的可执行文件
应用程序/main.cpp
#include <QApplication>
#include "gui/mainWindow.hpp"
int main(int argc, char *argv[]) {
QApplication app{argc, argv};
MainWindow gui{};
gui.show();
return app.exec();
}
使用以下 CMakelists.txt 我链接到 gui lib
cmake_minimum_required (VERSION 3.5.1 FATAL_ERROR)
project (app)
add_executable(${PROJECT_NAME}
main.cpp
)
target_include_directories(${PROJECT_NAME}
PUBLIC ${PROJECT_BINARY_DIR}
)
target_link_libraries(${PROJECT_NAME}
PRIVATE
gui::gui
Qt5::Widgets
Qt5::Core
Qt5::Xml
Qt5::OpenGL
Qt5::Gui
)
install(TARGETS ${PROJECT_NAME}
DESTINATION bin)
我项目的顶级 CMakeLists 如下所示
cmake_minimum_required (VERSION 3.5.1 FATAL_ERROR)
project(project)
set(CMAKE_INSTALL_DIR ${PROJECT_SOURCE_DIR}/obj)
set(CMAKE_INSTALL_PREFIX ${CMAKE_INSTALL_DIR})
# add our local path to the runtime path
SET(CMAKE_INSTALL_RPATH "$ORIGIN:${CMAKE_INSTALL_PREFIX}/lib")
# also add the link paths to the runtime paths
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
find_package(Qt5 COMPONENTS Core Widgets Xml OpenGL Gui REQUIRED)
## --> Build libraries and applications <--
add_subdirectory(gui)
add_subdirectory(apps)