在 QtCreator 中 运行 时 CMake 找不到忍者

CMake cannot find ninja when run in QtCreator

我在 CMakeLists.txt 文件中调用了 find_program 以查找 Ninja 的路径。当我通过命令行 运行 ninja 时,这个 returns 是正确的值,但是当我在 QtCreator 中 运行 它时失败:

find_program(
    CMAKE_MAKE_PROGRAM
    NAME ninja
    PATHS /opt/local/bin
  )
  message(${CMAKE_MAKE_PROGRAM})

在忍者这个returns:

/opt/local/bin/ninja

在 QtCreator 中这个 returns:

/usr/bin/make

为什么 CMake 找不到 $PATH 中存在的内容?

变量 CMAKE_MAKE_PROGRAM 由 CMake 生成器缓存find_program 不会更新缓存变量,除非它包含 *-NOTFOUND.

您需要在 find_program 调用中使用其他变量,然后将 CMAKE_MAKE_PROGRAM 变量更新为 set(CACHE ... FORCE):

set(CMAKE_MAKE_PROGRAM <new-value> CACHE FILEPATH "" FORCE)

请注意,将 CMAKE_MAKE_PROGRAMmake 切换到 ninja 并不是更改 CMake generator 的正确方法。您需要通过 -G 选项将正确的 CMake 生成器传递给 cmake 本身。

来自 find_program() 的文档:

A cache entry named by VAR is created to store the result of this command. If the program is found the result is stored in the variable and the search will not be repeated unless the variable is cleared.

在你的情况下 CMAKE_MAKE_PROGRAM 恰好被缓存为 /usr/bin/make(可能是 QtCreator 设置的某个点),所以 find_program() 什么都不做。

makeninja 之间切换的正确方法是使用 CMake generators.