CMake如何避免递归add_subdirectory?

时间:2017-12-20 18:43:40

标签: cmake

我的工作区结构为

workspace
  library1
  library2
  library3

library3取决于library2library1

library2取决于library1

library3 CMakeLists.txt

cmake_minimum_required (VERSION 3.9)
add_subdirectory(../library2 ${CMAKE_CURRENT_SOURCE}/../library2/build)
add_subdirectory(../library1 ${CMAKE_CURRENT_SOURCE}/../library1/build)

library2 CMakeLists.txt

cmake_minimum_required (VERSION 3.9)
add_subdirectory(../library1 ${CMAKE_CURRENT_SOURCE}/../library1/build)

library2中的cmake会引发library1/build已包含cmake文件的错误。

CMake Error at C:/Users/me/workspace/Library2/CMakeLists.txt:12 (add_subdirectory):
  The binary directory

    C:/Users/me/workspace/Library1/build

  is already used to build a source directory.  It cannot be used to build
  source directory

    C:/Users/me/workspace/Library1

  Specify a unique binary directory name.

1 个答案:

答案 0 :(得分:1)

我个人会为此类事做的是,在workspace中,我有一个根CMakeList.txt文件来设置项目:

# Set the minimum version of cmake required
cmake_minimum_required(VERSION 3.9)
project(MyProject)
add_subdirectory(library1)
add_subdirectory(library2)
add_subdirectory(library3)

(这真的是你所需要的,你的根CMakeLists.txt文件根本不需要很长时间。)

然后,不是调用相对路径add_subdirectory()调用,而是针对需要依赖项的库,使用add_dependencies(<target> \[<target-dependency>\]...)来确保在当前目标之前构建依赖项目标。

因此,在您的add_library/add_executabletarget_link_libraries电话(如果适用)之后,在library3 / CMakeLists.txt内添加:

add_dependencies(library3 general path/to/library2 general path/to/library1

作为一个例子。