首页 > 解决方案 > 构建树中具有多个 CMakeLists 的 CMakeLists

问题描述

我有以下树:

/all-targets
----CMakeLists.txt
----/target1
--------CMakeLists.txt
--------/include
--------/src
----/target2
--------CMakeLists.txt
--------/include
--------/src
----/target3
--------CMakeLists.txt
--------/include
--------/src

顶级 CMake 应该能够将所有目标链接在一起,而无需生成任何可执行文件或库文件,只生成具有正确结构/树的任何项目类型

target1 需要具有来自 target2 的库/目标文件,以便可以对其进行编译。

我读过这些: 1.多个 CMakeLists 2. CMake - 取决于另一个 cmake 项目

我现在了解的是在顶级 CMakeLists.txt 我可以添加add-subdirectory命令来添加 target1、target2 和 target3(子目录),但我仍然不明白我应该在 /target1/CmakeLists.txt 中添加什么所以它可以与target2库文件链接吗?我不认为这是add-subdirectory因为在这种情况下 target2 目录是兄弟目录而不是子目录。

顶级 CmakeLists.txt 文件是否理解我只想创建将目标链接在一起的项目文件而没有输出(可执行文件 - 库)。

标签: c++cmake

解决方案


你没有给我们太多继续,但我可以提供一个大致的想法。

顶级 CMakeLists 只是调用add_subdirectory各种目标。这些应该被排序,使得没有目标依赖于它之后的目标。

对于 target1,您可以拥有以下内容:

add_library(target1_common STATIC oven.cpp pan.cpp tray.cpp)
target_include_directories(target1_common PUBLIC include)
add_executable(target1 target1_main.cpp)
target_link_libraries(target1 PRIVATE target1_common)

你说target2依赖于target1的某些部分,所以:

add_library(target2_common STATIC table.cpp chair.cpp plate.cpp)
target_include_directories(target2_common PUBLIC include)
target_link_libraries(target2_common PUBLIC target1_common)

add_executable(target2 target2_main.cpp)
target_link_libaries(target2 PRIVATE target2_common)

可执行文件已链接PRIVATE,因为您不会进一步链接到它们,但PUBLIC也可以正常工作。

编辑:添加target_include_directories了自动填充标题搜索路径的语句target1_commontarget2_common


推荐阅读