Ninja

1.13.0 · active · verified Sun Mar 29

Ninja is a small build system focused on speed, typically used with higher-level build systems like CMake to manage large projects. The Python package `ninja` provides the `ninja` executable and the `ninja_syntax.py` module for generating `.ninja` build files programmatically. It is currently at version 1.13.0 and actively maintained by scikit-build.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `ninja_syntax` to programmatically generate a `build.ninja` file for a simple C project, and then execute the `ninja` command to build it. Ensure you have a C compiler (like `gcc`) installed and that `ninja` (the executable) is in your system's PATH.

import subprocess
from ninja_syntax import Writer
import os

# Create a simple build.ninja file
with open('build.ninja', 'w') as f:
    writer = Writer(f)
    writer.variable('cflags', '-Wall -Wextra')
    writer.rule('cc', 'gcc $cflags -c $in -o $out')
    writer.rule('link', 'gcc $in -o $out')
    writer.build('hello.o', 'cc', 'hello.c')
    writer.build('hello', 'link', 'hello.o')
    writer.default('hello')

# Create a dummy source file
with open('hello.c', 'w') as f:
    f.write("""
#include <stdio.h>

int main() {
    printf("Hello, Ninja!\n");
    return 0;
}
""")

print("Generated build.ninja and hello.c. Running ninja...")

try:
    # Run ninja
    result = subprocess.run(['ninja'], capture_output=True, text=True, check=True)
    print("Ninja build successful!")
    print("\nStdout:\n", result.stdout)
    if result.stderr:
        print("\nStderr:\n", result.stderr)

    # Optionally, run the built executable
    print("\nRunning built executable...")
    exec_result = subprocess.run(['./hello'], capture_output=True, text=True, check=True)
    print("Executable output:\n", exec_result.stdout)

except subprocess.CalledProcessError as e:
    print(f"Ninja build failed with error: {e}")
    print("\nStdout:\n", e.stdout)
    print("\nStderr:\n", e.stderr)
except FileNotFoundError:
    print("Error: 'ninja' command not found. Please ensure Ninja is installed and in your PATH.")

# Clean up generated files (optional)
# os.remove('build.ninja')
# os.remove('hello.c')
# if os.path.exists('hello.o'):
#     os.remove('hello.o')
# if os.path.exists('hello'):
#     os.remove('hello')

view raw JSON →