# CMake where one can build from the directory itself or from the root cmake

**URL:** https://discourse.cmake.org/t/cmake-where-one-can-build-from-the-directory-itself-or-from-the-root-cmake/5399
**Category:** Usage
**Created:** [April 7, 2022, 2:34pm UTC](https://discourse.cmake.org/t/cmake-where-one-can-build-from-the-directory-itself-or-from-the-root-cmake/5399 "2022-04-07T14:34:56Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Joel](https://discourse.cmake.org/user_avatar/discourse.cmake.org/joel/32/1908_2.png) [@Joel](https://discourse.cmake.org/u/Joel)
#### Post date: [April 7, 2022, 2:34pm UTC](https://discourse.cmake.org/t/cmake-where-one-can-build-from-the-directory-itself-or-from-the-root-cmake/5399/1 "2022-04-07T14:34:56Z")

</div>

Hi,

I have a question about using CMake for a repository, with a root cmake at the top which `add_subdirectory()`'s all the directories. However, I would also like to be able to build from individual directories without resorting to add\_subdirectory on a non subdirectory, which sometimes messes up the build layout - e.g.

`/CMakeLists.txt`

```auto
project(main)

add_subdirectory(lib1/)
add_subdirectory(lib2/) 
add_subdirectory(program1/)
add_subdirectory(program2/)

```

`/lib1/CMakeLists.txt`

```auto
project(lib1)
add_library(lib1 ...)

```

`/program1/CMakeLists.txt`

```auto
project(program1)
add_subdirectory(../lib1 ${PROJECT_BINARY_DIR}/lib1) #!!!

add_executable(program1)
target_link_libraries(program1 lib1)

```

[An issue with this is if I set EXCLUDE\_FROM\_ALL on `lib1` in the root cmake, `lib1` ends up being built in `/program1/lib1`]

Is it possible to:

1. Write the CMakeLists.txt in such a way to be able to build `program1` from the program1 folder instead of the root without have to resort to the ugly `add_subdirectory(../lib1 ${PROJECT_BINARY_DIR}/lib1)`
2. Build only selected targets from the root cmake without needing the dependencies of other subdirectories? e.g. if `/lib2` requires some dependency that I don’t have on my system, but I only want to build `program1` (which also builds `lib1`) - is this possible from the root?

Thank you!

---

<div class="post-metadata">

### Author: ![ben.boeckel](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/b/ea5d25/32.png) [@ben.boeckel](https://discourse.cmake.org/u/ben.boeckel)
#### Post date: [April 9, 2022, 12:53pm UTC](https://discourse.cmake.org/t/cmake-where-one-can-build-from-the-directory-itself-or-from-the-root-cmake/5399/2 "2022-04-09T12:53:29Z")

</div>

No, there’s no built-in way to do such things. I’d recommend figuring out what you want your project lines to be and structure the repo that way. Supporting arbitrary root directories isn’t really worth it IME because your “how to build” docs get really complicated (or you make “anything” work and the code is really complicated).
