Skip to main content

Git Submodules Guide

This guide explains how to manage dependent repositories (<submodule1> and <submodule2>) inside the main <project> repo using Git submodules.

1️⃣ Clone the Main Repo

  • Clones only the main repo. Submodules are not fetched yet.

2️⃣ Add Dependent Repos as Submodules

  • This creates .gitmodules automatically.
  • .gitmodules maps the submodule folder paths to the repo URLs.
Example .gitmodules content:

3️⃣ Commit Submodules in Main Repo

  • This stores the submodule references (commit pointers) in the main repo.
  • Important: It does not include the actual submodule code in the main repo.

4️⃣ Workflow for Making Changes

A. Make changes in a submodule

B. Update the main repo pointer

✅ This ensures the main repo points to the latest commit in the submodule.

C. Make changes in the main repo

  • Edit files outside submodule folders as usual:
  • Submodule references remain unchanged unless you explicitly update them.

5️⃣ Pulling Updates

A. Pull main repo updates

  • Updates main repo content and submodule commit pointers (but not submodule content).

B. Pull submodule updates

  • --init --recursive → fetches submodules after a fresh clone.
  • --remote --merge → updates submodules to latest commits from their remote repos.

6️⃣ Fresh Clone with Submodules

To clone and have submodules ready automatically:
  • This populates <submodule1-folder> and <submodule2-folder> folders.

7️⃣ Optional: Setup Script

You can create a setup.sh for developers:
Usage:

8️⃣ Key Notes

  1. Submodule commits are independent — changes inside submodules must be committed and pushed inside the submodule repo.
  2. Main repo only tracks submodule commit pointers.
  3. .gitmodules contains mapping info: submodule path → repo URL.
  4. Fresh clones require git submodule update --init --recursive to populate submodules.
  5. Use git submodule update --remote --merge to sync submodules with the latest remote commits.