Is there a way to set a variable in a CMake script to the output of a shell command?
Something like SET(FOO COMMAND "echo bar")
would come to mind
Asked
Active
Viewed 4.4k times
1 Answers
107
You want the execute_process
command.
In your case, on Windows:
execute_process(COMMAND CMD /c echo bar OUTPUT_VARIABLE FOO)
or on Linux, simply:
execute_process(COMMAND echo bar OUTPUT_VARIABLE FOO)
In this particular case, CMake offers a cross-platform solution. CMake can itself be used to run commands that can be used on all systems, one of which is echo
. To do this, CMake should be passed the command line arg -E
. For the full list of such commands, run cmake -E help
Inside a CMake script, the CMake executable is referred to by ${CMAKE_COMMAND}
, so the script needs to do:
execute_process(COMMAND ${CMAKE_COMMAND} -E echo bar OUTPUT_VARIABLE FOO)
-
17Depending on the command you execute, it may set trailing whitespaces to the variable. If this behaviour is not desirable, you can use the option OUTPUT_STRIP_TRAILING_WHITESPACE as the last argument to the 'execute_process' function. – hbobenicio Jan 27 '17 at 03:46
-
4@hbobenicio `OUTPUT_STRIP_TRAILING_WHITESPACE` is more or less **required** IMO – Trevor Boyd Smith May 22 '18 at 15:00
-
8If your command is more than a simple program call, use `COMMAND bash "-c" "your_complex.sh | command && stuff"`. Credit: https://stackoverflow.com/a/35695350/5470596 – YSC Jan 10 '19 at 16:47