Issue
As part of the configuration process of my project, I need to query a command line tool with execute_process
to retrieve a variable required by the rest of the flow. The input to this query depends on a configuration option.
The particular command invoked by execute_process
happens to be fairly expensive, so I would like to avoid rerunning it unless the input has changed.
How do I "cache" the result of execute_process
so it's only rerun if a certain CMake option changes (i.e., instead of whenever anything changes that would trigger CMake to run again)?
Example code:
set(MY_INPUT_VARIABLE "my_default" CACHE STRING "Used by command line tool.")
# This should only be re-run if MY_INPUT_VARIABLE changed since last time it was run
execute_process(COMMAND slow_executable ${MY_INPUT_VARIABLE} OUTPUT_VARIABLE RESULT)
Solution
Copy the value to a INTERNAL
cache variable and compare it with the current version of the cache variable.
set(MY_INPUT_VARIABLE "my_default" CACHE STRING "Used by command line tool.")
set(MY_INPUT_VARIABLE_INTERNAL "" CACHE INTERNAL "for internal use only; do not modify")
if (NOT MY_INPUT_VARIABLE STREQUAL MY_INPUT_VARIABLE_INTERNAL)
execute_process(COMMAND slow_executable ${MY_INPUT_VARIABLE} OUTPUT_VARIABLE RESULT)
set(MY_INPUT_VARIABLE_INTERNAL ${MY_INPUT_VARIABLE} CACHE INTERNAL "for internal use only; do not modify")
endif()
Note that you could also use a different kind of cache variable, but you'd need to use FORCE
to overwrite the value. In addition to this such a cache variable would be displayed by cmake-gui.
Answered By - fabian