Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

cmake

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

like image 645
Sasha Avatar asked Oct 23 '12 18:10

Sasha


People also ask

How do you set a variable value in Cmake?

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) .

How do I run a command in Cmake?

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.

What is ${} in Cmake?

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.

How do I use environment variables in Cmake?

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.


1 Answers

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) 
like image 196
Fraser Avatar answered Oct 08 '22 14:10

Fraser