CMake: How to automatically git submodule update --init
When you are using git submodules in your CMake project, you might want to ensure that the submodules are initialized and updated automatically when configuring the project. You can achieve this by adding a custom command in your CMakeLists.txt
file.
CMakeLists.txt
# Try to initialize git submodules automatically during configure so
# downstream consumers don't need a separate manual step. This is best-effort
# and will only run when Git is available.
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()
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow