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>

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

Useful extra commands

comments powered by Disqus