0%

cmake execute_process 用法

cmake execute_process 用法

原文档

  1. https://cmake.org/cmake/help/latest/command/execute_process.html
  2. Runs the given sequence of one or more commands.
  3. Commands are executed concurrently as a pipeline, with the standard output of each process piped to the standard input of the next. A single standard error pipe is used for all processes.
  4. COMMAND
    1. A child process command line.
    2. CMake executes the child process using operating system APIs directly. All arguments are passed VERBATIM to the child process. No intermediate shell is used, so shell operators such as > are treated as normal arguments. (Use the INPUT_*, OUTPUT_*, and ERROR_* options to redirect stdin, stdout, and stderr.)
    3. If a sequential execution of multiple commands is required, use multiple execute_process() calls with a single COMMAND argument.

总结如下

  1. 虽然文中说会被逐字传递给子进程, 但是, 以${} 包围的代码会被提前解析, 使用cmake 中的值替代
    1. 也可以使用环境变量传递
  2. 可以运行多个命令
  3. 但是上一个命令的标准输出会被管道发送到下一个命令的标准输入
    1. 所以多个Command 都有输出的话, 只有最有一个的输出会被保存到OUTPUT_VARIABLE
    2. 前面的都传入给下一个了
  4. 如果需要多个命令的输出, 使用多个execute_process, 每个包含一个Command

实际使用注意点

  1. COMMAND 并不是按照shell执行的, 而是直接起一个进程, 执行输入的命令
    1. 所以COMMAND echo $PATH 会直接输出 $PATH, 而非解析 $PATH 值, 因为这是在直接执行 echo 可执行程序, 环境变量的解析 是shell干的活
      1. 这里没有shell
  2. 需要执行shell命令的 使用类似 COMMAND sh -c "echo $PATH"
    1. 这样会起一个sh进程, 再由sh进程执行 echo 命令, 这样就有环境变量了

一个接受参数的并使用的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 设置参数
# env 中设置 参数, COMMAND 可以通过 $ARG_TO_PASS 获取, 但是 ${ARG_TO_PASS} 会被提前解析, 传入cmd 中的时候, 就已经是 它的值了
set(ENV{ARG_TO_PASS} "from cmake, env var")
set(ARG_TO_PASS "this is cmake var")

execute_process(
# 有了sh 后 就可以使用sh中带不带括号的方式获取变量了
# 但是注意: $ARG_TO_PASS 和 cmake 中的变量没关系, 已经被设置为系统环境变量了
# ${ARG_TO_PASS} 在执行前, 已经被cmake 替换了, 传入的就是 "this is cmake var"
COMMAND sh -c "echo $ARG_TO_PASS ------ ${ARG_TO_PASS}"
OUTPUT_VARIABLE _RES
ERROR_VARIABLE _RES
ERROR_QUIET
)
message("run result: ${_RES}")

输出

1
run result: from cmake, env var ------ this is cmake var