我有一个Qt小部件C++类,该类加载在Qt Creator中创建的ui文件。该类的标题和源文件位于两个单独的目录中。我在指示cmake/automoc查找该类的标题时遇到麻烦。 cmake认识到它需要移动C++文件,但找不到类似的 header 。

我可以做些什么来帮助cmake查找文件吗?

如果cpp和头文件都在同一目录中,则一切正常。仅在 header 位于其他位置时才会出现。

我的目录结构是

project
    src
        include
            Foo
                Bar.h
    lib
        Foo
            Bar.cpp
            forms
                Bar.ui

在src/include/Foo/Bar.h中,我有:
// Bar.h
#include <QtWidgets/QWidget>

namespace Ui { class Bar; }

class Bar : public QWidget {
    Q_OBJECT
    ...
}

在src/Foo/Bar.cpp文件中:
#include "Foo/Bar.h"
#include "moc_Bar.cpp"
#include "ui_Bar.h"

我在src/lib/Foo中的CMakeLists.txt设置如下:
# there is a project() call at the root that defines PROJECT_SOURCE_DIR
set(PUBLIC_HEADERS_DIR ${PROJECT_SOURCE_DIR}/src/include)

# Pick up public library headers
include_directories(${PUBLIC_HEADERS_DIR})

# Pick up private headers in library dir
include_directories(${CMAKE_CURRENT_SOURCE_DIR})

# Set up Qt
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
find_package(Qt5Core REQUIRED)
find_package(Qt5Gui REQUIRED)
find_package(Qt5Widgets REQUIRED)
include_directories(${Qt5Core_INCLUDE_DIRS})
include_directories(${Qt5Gui_INCLUDE_DIRS})
include_directories(${Qt5Widgets_INCLUDE_DIRS})
add_definitions(${Qt5Widgets_DEFINITIONS})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Widgets_EXECUTABLE_COMPILE_FLAGS}")

# Set up Qt forms/resources
qt5_wrap_ui(UI_OUT_FILES forms/Bar.ui)
qt5_add_resources(RESOURCE_FILE resources.qrc)

# Library cpp and header files
set(CORE_CPP_FILES Bar.cpp)
set(LIB_CPP_FILES ${LIB_CPP_FILES} ${CORE_CPP_FILES} ${UI_OUT_FILES} ${RESOURCE_FILE})
set(LIB_HEADER_FILES ${PUBLIC_HEADERS_DIR}/Foo/Bar.h)

# Build library
add_library(Foo SHARED ${LIB_CPP_FILES} ${LIB_HEADER_FILES})
target_link_libraries(Foo ${Qt5Widgets_LIBRARIES})

运行cmake时,出现以下错误:

AUTOGEN:错误:/automoc/src/lib/Foo/Bar.cpp该文件包含moc文件“moc_Bar.cpp”,但找不到 header “Bar {.h,.hh,.h++ ,. hm,.hpp ,.hxx,.in,.txx}”放在/automoc/src/lib/Foo/

最佳答案

您必须手动包装头文件。
将其放入您的CMakeLists.txt:

file(GLOB HEADERS_TO_MOC src/include/Foo/ *.h)

qt5_wrap_cpp(PROCESSED_MOCS
             ${HEADERS_TO_MOC}
             TARGET Foo
             OPTIONS --no-notes) # Don't display a note for the headers which don't produce a moc_*.cpp

target_sources(Foo PRIVATE ${PROCESSED_MOCS}) # This adds generated moc cpps to target

这种方法的真实示例
https://github.com/paceholder/nodeeditor/blob/master/CMakeLists.txt#L133

关于qt - 如何指示cmake/automoc查找外部 header ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28492423/

10-13 08:09