Issue
Is this the right idiom to discover a variable value and cache it only if it hasn't been cached already? Using the path type is just for example purposes.
IF(NOT $CACHE{PATH_CACHED})
#discover the PATH_CACHED value and store it in PATH_NORMAL
SET(PATH_CACHED ${PATH_NORMAL} CACHE FILEPATH "My path")
ENDIF(NOT $CACHE{PATH_CACHED})
Solution
Use if (NOT DEFINED)
, like so:
if (NOT DEFINED PATH_CACHED)
# do something expensive to compute PATH_CACHED as a normal
# variable
endif ()
set(PATH_CACHED "${PATH_CACHED}"
CACHE FILEPATH "My path")
Two main points here:
- Using
if (NOT DEFINED X)
is a more precise check thanif (NOT X)
since someone might want to setX
to empty. - Unconditionally setting
PATH_CACHED
to the computed normal variable has more consistent behavior across a range of CMake versions and also preserves the behavior of adjusting a path relative to the process working directory when an untyped cache variable (set on the command line as-DPATH_CACHED=foo
) gets a type ofPATH
orFILEPATH
. See the docs here: https://cmake.org/cmake/help/latest/manual/cmake.1.html#cmdoption-cmake-D
Also there hasn't been any need to use all-caps command names or to repeat the condition in endif()
for almost twenty years.
Answered By - Alex Reinking Answer Checked By - Pedro (WPSolving Volunteer)