Git submodules allow you to embed one Git repository inside another while keeping both repositories independent. The main repository is called the superproject, and the embedded repository is called a submodule. This approach is commonly used for managing external libraries or shared components without merging their entire commit history into your project.
Submodules are stored as references to specific commits of another repository. Git does not automatically update submodules unless explicitly told to do so. This ensures controlled dependency versions.
// Add a new submodule to the repository
git submodule add <repository-url> <path-to-submodule>
// Example: Adding a library as a submodule
git submodule add https://github.com/example/library.git libs/library
// Clone repository and automatically initialize submodules
git clone --recurse-submodules <repository-url>
// Initialize submodules after cloning
git submodule update --init --recursive
These commands ensure that all submodules are checked out at the exact commit referenced by the superproject, preventing version mismatches.
// Show current commit and status of submodules
git submodule status
// Update submodule to latest remote commit
git submodule update --remote <submodule-name>
// Commit changes inside submodule and update reference
cd libs/library
git commit -am "Update submodule content"
cd ../../
git add libs/library
git commit -m "Updated submodule reference"
// Deinitialize submodule
git submodule deinit <submodule-path>
// Remove submodule from index
git rm <submodule-path>
// Commit submodule removal
git commit -m "Remove submodule"
// Delete remaining submodule files
rm -rf <submodule-path>