61

Is It possible to include sibling directory as Sub-Directory inside cmake ?

Something like

A 
  CMakeLists.txt

B
  CMakeLists.txt

and B includes A as sub-directory ?

Vivek Goel
  • 22,942
  • 29
  • 114
  • 186

2 Answers2

115

It is possible, although perhaps not recommended...

You can use the two-argument form of the add_subdirectory command to add any directory you want as a "sub" directory:

add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../A ${CMAKE_CURRENT_BINARY_DIR}/A)

The second argument of the two-argument form specifies where to put the binary directory for the added subdirectory.

You just have to be careful that there's not also another real sub-directory of B that is also named "A" and that is also add_subdirectory'd... Because if you do, then that would be an error, as CMake cannot have two different source directories mapping into the same build directory.

DLRdave
  • 13,876
  • 4
  • 53
  • 70
  • What if `${CMAKE_CURRENT_SOURCE_DIR}/../A/some/path` is used? Will it not avoid the error of name clash? – Fauzan Feb 04 '18 at 06:57
  • Whether or not there's a name clash depends on the full set of directories being used in the sum of all add_subdirectory calls. And on the contents of the CMakeLists.txt files. For example, "project" commands introduce source_dir and binary_dir variables based on the name of the project. Using "../A/some/path" will avoid a conflict with another "A", but not with another "path" – DLRdave Feb 05 '18 at 15:46
  • you could simply use the absolute path. why didnt you do that ? is there a reason behind your choice here? – Hossein Sep 26 '20 at 13:23
  • @Rika using absolute path is certainly possible. I never recommend it because of the simple fact that absolute path is always different from platform to platform, and very likely different from developer to developer. In general, you have ZERO knowledge of how your code will be laid out on a developer's disk, other than the structure that exists inside your repository. – DLRdave Sep 28 '20 at 13:24
  • @DLRdave You are certainly 100% right. thanks for the reply I apprecaite it – Hossein Sep 28 '20 at 13:29
3

Unfortunately, no.

As solution i may suggest you to add_subdirectory(A) and add_subdirectory(B) at the top level and set vars you want to export from A with PARENT_SCOPE. This would allow B/CMakeLists.txt to access varibles defined in A/CMakeLists.txt

arrowd
  • 33,231
  • 8
  • 79
  • 110