# How to get access cmake variable in a header file

**URL:** <https://discourse.cmake.org/t/how-to-get-access-cmake-variable-in-a-header-file/7125>\
**Category:** Code\
**Tags:** os:linux\
**Created:** [December 23, 2022, 9:27pm UTC](https://discourse.cmake.org/t/how-to-get-access-cmake-variable-in-a-header-file/7125 "2022-12-23T21:27:01Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![surfmich](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/s/b4bc9f/32.png) [@surfmich](https://discourse.cmake.org/u/surfmich)\
**Post date:** [December 23, 2022, 9:27pm UTC](https://discourse.cmake.org/t/how-to-get-access-cmake-variable-in-a-header-file/7125/1 "2022-12-23T21:27:01Z")

</div>

I want want to access a cmake variable in a header file. I was able to use add\_compile\_definition() to create a preprocessor definition based on a cmake variable that I could use in a cpp file, but when I try the same mechanism in a header file it doesn’t work.

---

<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:** [December 28, 2022, 12:37pm UTC](https://discourse.cmake.org/t/how-to-get-access-cmake-variable-in-a-header-file/7125/2 "2022-12-28T12:37:33Z")

</div>

You’ll want `configure_file()` for this:

```nohighlight
#cmakedefine DEF_OR_UNDEF
#cmakedefine DEF_WITH_VALUE @value@
#cmakedefine01 TRUE_OR_FALSE

```

CMake:

```cmake
set(DEF_OR_UNDEF 0) # will be `// #undef DEF_OR_UNDEF`
set(value 5)
set(DEF_WITH_VALUE 1) # will be `#define DEF_WITH_VALUE 5`
set(TRUE_OR_FALSE OFF) # will be `#define TRUE_OR_FALSE 0`

```

---

<div class="post-metadata">

**Author:** ![surfmich](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/s/b4bc9f/32.png) [@surfmich](https://discourse.cmake.org/u/surfmich)\
**Post date:** [January 2, 2023, 2:02pm UTC](https://discourse.cmake.org/t/how-to-get-access-cmake-variable-in-a-header-file/7125/3 "2023-01-02T14:02:12Z")

</div>

Thanks Ben. To be clear, those #cmakedefine statements need to go into a \*.in.h file which configure\_file() will then use to create a header file which I need to include? Said otherwise, there’s no getting around creating another header file?

---

<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:** [January 3, 2023, 10:08pm UTC](https://discourse.cmake.org/t/how-to-get-access-cmake-variable-in-a-header-file/7125/4 "2023-01-03T22:08:23Z")

</div>

Yes, they should go on the source side of the `configure_file` command. And no, you need to communicate through a header file (or some other files that is `#include`’d).
