Skip to content

Instantly share code, notes, and snippets.

@olibartfast
Last active August 28, 2025 10:58
Show Gist options
  • Select an option

  • Save olibartfast/8e79a4fb4343915cf1710492c2d41f59 to your computer and use it in GitHub Desktop.

Select an option

Save olibartfast/8e79a4fb4343915cf1710492c2d41f59 to your computer and use it in GitHub Desktop.
Ninja Build System Tutorial for C++ Projects

Ninja Build System Tutorial for C++ Projects

What is Ninja?

Ninja is a small, fast build system designed to have its input files generated by a higher-level build system (like CMake). It's optimized for speed and is particularly useful for large C++ projects.

Basic Setup

1. Generate Ninja files with CMake:

# Create build directory
mkdir build && cd build

# Generate Ninja build files
cmake -G Ninja ..

# Or specify build type
cmake -G Ninja -DCMAKE_BUILD_TYPE=Release ..

2. Build the project:

# Build everything
ninja

# Build specific target
ninja target_name

# Build with verbose output
ninja -v

# Build using multiple cores (default: all available)
ninja -j 8

Common Commands

# Clean build artifacts
ninja clean

# List all available targets
ninja -t targets

# Show dependency graph
ninja -t graph | dot -Tpng -o deps.png

# Show build rules
ninja -t rules

# Dry run (show what would be built)
ninja -n

Example Workflow

# Initial setup
git clone your-cpp-project
cd your-cpp-project
mkdir build && cd build

# Configure with CMake
cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug ..

# Build
ninja

# Run tests (if available)
ninja test

# Install (if configured)
ninja install

Advantages over Make

  • Speed: Parallelizes builds efficiently
  • Simplicity: Minimal syntax, fast parsing
  • Dependency tracking: Accurate incremental builds
  • Cross-platform: Works on Linux, macOS, Windows

Tips

  • Always use a separate build directory
  • Ninja files are generated - don't edit them manually
  • Use ninja -C build_dir to build from any directory
  • For debugging: ninja -v shows full command lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment