如何使用cmake强制UIC在源码目录下生成ui_mainwindow.h

How to force UIC to generate ui_mainwindow.h in the source directory using cmake

UIC 成功创建了 ui_mainwindow.h 文件,但将其存储在构建目录中。这会导致编译时错误 'ui_mainwindow.h: No such file or directory found'。

如果我在构建目录中添加 ui_mainwindow.h 文件的完整路径,cmake (catkin_make) 会成功构建项目。显然我想避免在我的源代码中使用头文件的绝对路径。

我的CMakeLists的相关部分:

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 REQUIRED COMPONENTS Widgets Core )
add_executable(monitor src/mainwindow.cpp src/main.cpp src/mainwindow.ui)
qt5_use_modules(monitor Widgets)

target_link_libraries(monitor Qt5::Core Qt5::Widgets ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${OpenCV_LIBRARIES} ${OpenCV_LIBS} )

如何强制 UIC 在我的源目录中构建 ui_mainwindow.h 文件。或者如何在 CMakeLists.txt

中包含 cmake 构建目录

我试过了

qt5_wrap_ui (monitor_UI src/mainwindow.ui OPTIONS -o 'ui_mainwindow.h')
add_executable(monitor src/mainwindow.cpp src/main.cpp ${monitor_UI})

没有成功。

AUTOGEN_BUILD_DIR CMake variable specifies where AUTOUIC should generate files. If you want the generated files to be placed in your current source directory, you can set it to CMAKE_CURRENT_SOURCE_DIR:

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set(AUTOGEN_BUILD_DIR ${CMAKE_CURRENT_SOURCE_DIR})

来自 CMake-Qt documentation 的关于将 AUTOUICAUTOGEN_BUILD_DIR 变量一起使用的附加注释:

The generated ui_*.h files are placed in the <AUTOGEN_BUILD_DIR>/include directory which is automatically added to the target’s INCLUDE_DIRECTORIES.

因此,您应该而不是必须在include_directories()命令中明确列出包含生成的headers的目录。

根据 hyde 的评论,我只是使用

在包含路径中添加了构建目录
include_directories(
  ${CMAKE_CURRENT_BINARY_DIR}
)

解决了我的问题。