How do I initialize a CMake variable with the result of a shell command

Cmake

Cmake Problem Overview


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

Cmake Solutions


Solution 1 - Cmake

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSashaView Question on Stackoverflow
Solution 1 - CmakeFraserView Answer on Stackoverflow