Using .gitignore
Learn how to exclude build directories and binaries from your Git repository, keeping your C++ projects clean and efficient.
What Is .gitignore?
A .gitignore file is a plain text file placed at the root of your Git repository. It tells Git which files and directories to intentionally ignore: they won't be tracked, staged, or committed.
Why Does It Matter for C++?
What C++ Projects Generate
The Core Rule
This principle applies beyond C++: Java's .class files, Python's __pycache__, and JavaScript's node_modules all follow the same logic.
Pattern Syntax
Tracked vs Untracked vs Ignored
| Tracked | Untracked | Ignored | |
|---|---|---|---|
| Git knows about it? | Yes | No | No |
| Shows in git status? | If modified | Yes | No |
| Included in commits? | When staged | If you add it | Never |
| Example | main.cpp | new_file.cpp | main.o |
Creating Your .gitignore
Example: Basic .gitignore
Example: CMake Project
Example: Negation Pattern
How Patterns Are Matched
Global vs Local .gitignore
| Local .gitignore | Global .gitignore | |
|---|---|---|
| Location | Project root | Home directory |
| Scope | One repository | All repositories |
| Shared with team? | Yes, committed | No, personal |
| Best for | Build artifacts, project output | OS files, IDE settings |
| Example entries | *.o, build/ | .DS_Store, Thumbs.db |
Advanced Pattern: ** Double Star
The ** pattern matches across any number of directories. It's powerful for ignoring files no matter where they appear in the project tree.
Already Tracked Files
Adding a pattern to .gitignore does not remove files that are already tracked. If you accidentally committed a build artifact, you need an extra step.
Common Mistakes
C++ .gitignore Cheat Sheet
| Pattern | What It Ignores | Category |
|---|---|---|
| *.o | Object files from compilation | Compiler |
| *.exe / *.out | Executable binaries | Linker |
| build/ | Entire build directory | Build System |
| *.a / *.so | Static and shared libraries | Libraries |
| .vscode/ | VS Code settings folder | IDE |
| *.swp | Vim swap files | Editor |
Question 1 of 5
What is the primary purpose of a .gitignore file?
Question 2 of 5
Which pattern would correctly ignore all object files (files ending in .o) in a C++ project?
Question 3 of 5
You accidentally committed a build/ directory. You then add build/ to .gitignore. What happens?
Question 4 of 5
What does the ! prefix do in a .gitignore pattern?
Question 5 of 5
Which of these files should NOT typically be listed in a C++ project's .gitignore?