CMake:如何自动执行 git submodule update --init

在 CMake 项目中使用 git 子模块时,你可能希望在配置项目时自动初始化并更新这些子模块。可以通过在 CMakeLists.txt 文件中添加自定义命令来实现这一目标。

CMakeLists.txt
# 在配置期间尝试自动初始化 git 子模块,
# 这样下游使用者无需单独执行手动步骤。此为尽力而为,
# 仅在 Git 可用时才会运行。
find_package(Git QUIET)
if(GIT_FOUND)
  message(STATUS "Git found: initializing/updating submodules...")
  execute_process(
    COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    RESULT_VARIABLE _git_submodule_result
    OUTPUT_QUIET ERROR_QUIET
  )
  if(NOT _git_submodule_result EQUAL 0)
    message(WARNING "git submodule update --init --recursive failed with exit code ${_git_submodule_result}")
  endif()
else()
  message(STATUS "Git not found; skipping automatic git submodule initialization")
endif()

Check out similar posts by category: CMake, Git