How to add a Git submodule to your repository
A Git submodule lets you include another repository inside your own project. This is useful for reusing shared code, libraries, or dependencies across multiple projects.
To add a submodule to your parent repository, follow these steps:
Quick Steps
Step 1: Add the submodule
Run the following command in your parent repository (the one that will contain the submodule):
git submodule add <submodule-repo-url> <path>
<submodule-repo-url>is the URL of the repository you want to include as a submodule<path>is the directory inside your parent repository where the submodule will be placed.
Step 2: Commit the changes
When you add a submodule Git creates a new file named .gitmodules and the submodule directory, both of which should be staged and committed explicitly. For example:
git add .gitmodules <path>
git commit -m "Add submodule <name>"
git push
Step 3: Initialize and update after cloning
Initialize and update the referenced submodule after cloning. This step is crucial: when you clone a repo with submodules, the submodule directories are empty. This command downloads the actual submodule files so they’re usable:
git submodule update --init --recursive
Keep in mind: your parent repository stores a pointer to a specific commit SHA of the submodule, not the latest. When the submodule gets new commits, you need to explicitly update and commit the new reference.
Notes to remember
- Use
git submodule update --remoteto pull latest changes from the submodule repository. - Use
git clone --recurse-submodules <repo-url>command to also clone the submodules of a repository, when you clone the repository itself.
Useful extra commands
-
Update all submodules to the latest commit on their configured remote branches:
git submodule update --remote --merge -
Run a command in every submodule (example: pull main):
git submodule foreach 'git pull origin main'