c++ 如何使QtCreator CMake构建依赖于另一个CMake项目?

ujv3wf0j  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(321)

我有一个生成静态库的CMake项目。它在QtCreator中编译得很好,并在build dir中生成库。静态库的CMakeLists.txt如下所示:

cmake_minimum_required(VERSION 3.5)

project(mystaticlib VERSION 0.1 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

file(GLOB mystaticlib_SRC "src/**.cpp")
add_library( mystaticlib STATIC
    ${mystaticlib_SRC}
)
target_include_directories( mystaticlib PRIVATE include/mystaticlib INTERFACE include )

现在我有了一个Qt应用程序项目,我想让它依赖于另一个项目,这意味着我可以在QtProject中做一些类似的事情:

cmake_minimum_required(VERSION 3.25)

project(MyQtProject VERSION 0.1 LANGUAGES CXX)

# This is how I imagine it working, not an actual code
include_project(mystaticlib, "~/my_projects/mystaticlib/CMakeLists.txt")
set(HEADERS_mystaticlib get_project_headers(mystaticlib))
# end of made up code
add_executable(MyQtProjectEXE ${PROJECT_SOURCES})
target_link_libraries(MyQtProjectEXE mystaticlib)
target_include_directories(MyQtProjectEXE HEADERS_mystaticlib)

我怎样才能得到这样的东西呢?在实践中,我希望它能工作,这样依赖的项目目录可以在cmake配置步骤中设置为任何东西。

e3bfsja2

e3bfsja21#

您很可能对add_subdirectory感兴趣。
如果包含子目录有CMakeLists.txt,则按:

add_subdirectory("./path/to/the/directory")

您将包括该CMakeLists.txt文件中定义的所有目标。
您所要做的就是使用target_link_libraries添加一个依赖项,然后CMake就会知道需要事先构建子目录。
编辑:以您的项目为例:

cmake_minimum_required(VERSION 3.25)

project(MyQtProject VERSION 0.1 LANGUAGES CXX)

# This is how I imagine it working, not an actual code

#if the path is a subdirectory within the current folder
add_subdirectory("./local_path/to/mystaticlib")
#if not you need to specify a binary dir
add_subdirectory("/absolute/path/to/mystaticlib" "${CMAKE_CURRENT_BINARY_DIR}/mystaticlib")

set(HEADERS_mystaticlib get_project_headers(mystaticlib))
# end of made up code
add_executable(MyQtProjectEXE ${PROJECT_SOURCES})
target_link_libraries(MyQtProjectEXE mystaticlib)
#...

相关问题