1

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.
Necktwi
  • 2,483
  • 7
  • 39
  • 62
  • 1
    Possible duplicate of [How to handle a transitive dependency conflict using Git submodules and CMake?](https://stackoverflow.com/questions/42978414/how-to-handle-a-transitive-dependency-conflict-using-git-submodules-and-cmake) – Tsyvarev Dec 20 '17 at 19:36
  • Collision of build directory is only the first problem with `add_subdirectory()` with same source directory. Even if you overcome it, you will face with double target's definition. Referenced question describes how to avoid latter problem, and it will help in avoiding the former one. – Tsyvarev Dec 20 '17 at 19:39
  • Possible duplicate of [CMake: How to setup Source, Library and CMakeLists.txt dependencies?](https://stackoverflow.com/questions/31512485/cmake-how-to-setup-source-library-and-cmakelists-txt-dependencies) – Florian Dec 20 '17 at 19:47

1 Answers1

2

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.

Chris
  • 2,254
  • 8
  • 22