Necktwi
Necktwi

Reputation: 2617

CMake how to avoid recursive add_subdirectory?

My workspace is structured as

workspace
  library1
  library2
  library3

library3 depends on library2 and library1

library2 depends on library1

In 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)

In library2 CMakeLists.txt

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

cmake in library2 throws an error that library1/build already contains cmake files.

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.

Upvotes: 1

Views: 3131

Answers (1)

Chris
Chris

Reputation: 2304

What I would personally do for something like this, is that in workspace, I have a root CMakeList.txt file that sets up the project:

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

(This is really all you need, your root CMakeLists.txt file doesn't need to be long at all).

And then instead of calling relative path add_subdirectory() calls, then for the libraries that require dependencies, use add_dependencies(<target> \[<target-dependency>\]...) to ensure that the dependency targets are built before the current target.

So inside of library3/CMakeLists.txt, after your add_library/add_executable and target_link_libraries calls (if applicable) add:

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

As an example.

Upvotes: 2

Related Questions