# Use of include\_guard

**URL:** https://discourse.cmake.org/t/use-of-include-guard/9370
**Category:** Code
**Created:** [November 6, 2023, 12:34am UTC](https://discourse.cmake.org/t/use-of-include-guard/9370 "2023-11-06T00:34:37Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Andrew](https://discourse.cmake.org/user_avatar/discourse.cmake.org/andrew/32/2478_2.png) [@Andrew](https://discourse.cmake.org/u/Andrew)
#### Post date: [November 6, 2023, 12:34am UTC](https://discourse.cmake.org/t/use-of-include-guard/9370/1 "2023-11-06T00:34:37Z")

</div>

Is `include_guard` still expected to only work for `include` and not `add_subdirectory` (see [https://gitlab.kitware.com/cmake/cmake/-/issues/17895](https://gitlab.kitware.com/cmake/cmake/-/issues/17895) )?

We have a setup where modules `add_subdirectory` their direct dependencies, which often means that we get diamond inclusions (A adds B & C which both add D). We were originally protecting against this via `if( NOT target ) return() endif()`, but `include_guard(GLOBAL)` appeared to do this without adding extra boilerplate.

Nothing in [the `include_guard` documentation](https://cmake.org/cmake/help/v3.28/command/include_guard.html) explicitly makes a distinction between inclusion via `include` vs `add_subdirectory`.

---

<div class="post-metadata">

### Author: ![craig.scott](https://discourse.cmake.org/user_avatar/discourse.cmake.org/craig.scott/32/20_2.png) [@craig.scott](https://discourse.cmake.org/u/craig.scott)
#### Post date: [November 7, 2023, 4:00am UTC](https://discourse.cmake.org/t/use-of-include-guard/9370/2 "2023-11-07T04:00:43Z")

</div>

The explanation already given in the linked issue is pretty clear. Include guards are only for `include()`. The project must do its own logic to avoid calling `add_subdirectory()` on the same directory more than once. You _can_ call `add_subdirectory()` on the same source directory multiple times, but you must specify a different build directory for each call (the second argument to `add_subdirectory()`). I don’t think this is the situation you’re trying to set up though.

You might want to consider looking into [FetchContent](https://cmake.org/cmake/help/latest/module/FetchContent.html) which handles the diamond dependency pattern.
