在 CMake 中删除安装目标

Delete install target in CMake

我有一个 CMake-managed 项目,其中 从不 明智地在生成 Makefile 后执行 make install。此外,如果用户键入 make install 并在 /usr/local/include 的默认 CMAKE_INSTALL_PREFIX 中输入 headers,则未来的构建可能会受到污染。

我想指示 cmake 不要 在生成的 Makefile 中生成一个 install 目标。这可能吗?

注意:接近 this 的解决方案是 mark_as_advanced(CMAKE_INSTALL_PREFIX),但这仅 隐藏了 来自 ccmake 的选项。也许 set(CMAKE_INSTALL_PREFIX /dont/do/this)?

在 top-level CMakeLists.txt 的开头将 CMAKE_SKIP_INSTALL_RULES 设置为 ON(并附上注释解释原因)。正如文档中所说:

If TRUE, CMake will neither generate installation rules nor will it generate cmake_install.cmake files. This variable is FALSE by default.

证明此方法有效的快速交互:

$ cat CMakeLists.txt
cmake_minimum_required(VERSION 3.23)
project(test)

set(CMAKE_SKIP_INSTALL_RULES YES)

add_executable(app main.cpp)

$ cmake -S . -B build
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake --build build/ --target install
ninja: error: unknown target 'install'

尝试调用 install() 将发出以下警告:

CMake Warning in CMakeLists.txt:
  CMAKE_SKIP_INSTALL_RULES was enabled even though installation rules have
  been specified