如何使用 shell 命令的结果初始化 CMake 变量

有没有办法将 CMake 脚本中的变量设置为 shell 命令的输出? 像 SET(FOO COMMAND "echo bar")这样的东西会浮现在脑海中

40133 次浏览

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)