# Proper way to set a CACHE variable

**URL:** <https://discourse.cmake.org/t/proper-way-to-set-a-cache-variable/6222>\
**Category:** Code\
**Created:** [August 5, 2022, 6:13pm UTC](https://discourse.cmake.org/t/proper-way-to-set-a-cache-variable/6222 "2022-08-05T18:13:08Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![scottaronbloom](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/s/b4bc9f/32.png) [@scottaronbloom](https://discourse.cmake.org/u/scottaronbloom)\
**Post date:** [August 5, 2022, 6:13pm UTC](https://discourse.cmake.org/t/proper-way-to-set-a-cache-variable/6222/1 "2022-08-05T18:13:08Z")

</div>

I have shared library that I use where in its cmake files, sets a number of CACHE variables

the cmake file does something like

SET( VAR OFF CACHE BOOL “Some boolean variable” )  
MESSAGE( STATUS "VAR=${VAR} )  
in the project using the shared library, the shared librtary is added via add\_subdirectory

If I want to make sure a cache variable is set correctly, I know I can require it from the command line when calling cmake.

However, this is a setup set often forgotten. So I figured I should be able to do the following

SET( VAR ON )  
add\_directory( subdir )  
MESSAGE( STATUS “VAR=${VAR}” )

However, when I run cmake, I get  
VAR=OFF  
VAR=ON

Clearly Im doing something basic and wrong. The hack workaround I have done, is to  
SET( VAR ON CACHE BOOL “Some boolean” )  
in both places, but this just seems really wrong

---

<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:** [August 5, 2022, 11:51pm UTC](https://discourse.cmake.org/t/proper-way-to-set-a-cache-variable/6222/2 "2022-08-05T23:51:40Z")

</div>

What is the `cmake_minimum_required` you have set? I suspect policy [`CMP0126`](https://cmake.org/cmake/help/latest/policy/CMP0126.html) may be relevant here.

---

<div class="post-metadata">

**Author:** ![scottaronbloom](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/s/b4bc9f/32.png) [@scottaronbloom](https://discourse.cmake.org/u/scottaronbloom)\
**Post date:** [August 5, 2022, 11:57pm UTC](https://discourse.cmake.org/t/proper-way-to-set-a-cache-variable/6222/3 "2022-08-05T23:57:51Z")

</div>

Thank you. Looking at the docs it looks like using the new behavior will fix my issue!

---

<div class="post-metadata">

**Author:** ![scottaronbloom](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/s/b4bc9f/32.png) [@scottaronbloom](https://discourse.cmake.org/u/scottaronbloom)\
**Post date:** [August 12, 2022, 11:31pm UTC](https://discourse.cmake.org/t/proper-way-to-set-a-cache-variable/6222/4 "2022-08-12T23:31:55Z")

</div>

I finally got back to this. I was able to fix it. I did have to set the scope to the parent scope for the cache variable for it to fully work
