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
You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value , just cmake -D var=value or with cmake -C CMakeInitialCache. cmake . You can unset entries in the Cache with unset(... CACHE) .
Running a command at configure time It is generally a good idea to avoid hard coding a program path into your CMake; you can use ${CMAKE_COMMAND} , find_package(Git) , or find_program to get access to a command to run. Use RESULT_VARIABLE to check the return code and OUTPUT_VARIABLE to get the output.
Local Variables You access a variable by using ${} , such as ${MY_VARIABLE} . 1. CMake has the concept of scope; you can access the value of the variable after you set it as long as you are in the same scope. If you leave a function or a file in a sub directory, the variable will no longer be defined.
Use the syntax $ENV{VAR} to read environment variable VAR . To test whether an environment variable is defined, use the signature if(DEFINED ENV{<name>}) of the if() command. For general information on environment variables, see the Environment Variables section in the cmake-language(7) manual.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With