快才是王道

Ninja is a small build system with a focus on speed. It differs from other build systems in two major respects: it is designed to have its input files generated by a higher-level build system, and it is designed to run builds as fast as possible.

Ninja 非常簡約的首頁這樣地描述著自己。對我而言,它是絕佳的 make 替代品,因為它速度飛快而且語法簡潔易懂。

這是一個簡單的 build.ninja 範例:

cxx = g++
cflags = -g -Iinclude -Iout -I/usr/local/include -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -fno-exceptions -fno-rtti -fno-common -Woverloaded-virtual -Wcast-qual -L/usr/local/lib  -lpthread -lm -lLLVMX86Disassembler -lLLVMX86AsmParser -lLLVMX86CodeGen -lLLVMX86Desc -lLLVMSelectionDAG -lLLVMAsmPrinter -lLLVMMCParser -lLLVMX86AsmPrinter -lLLVMX86Utils -lLLVMX86Info -lLLVMJIT -lLLVMExecutionEngine -lLLVMCodeGen -lLLVMScalarOpts -lLLVMInstCombine -lLLVMTransformUtils -lLLVMipa -lLLVMAnalysis -lLLVMTarget -lLLVMMC -lLLVMCore -lLLVMSupport

rule flex
    command = flex -o $out $in

rule bison
    command = bison -d -o $out $in

rule cxx
    command = $cxx $cflags -o $out $in

build out/tokens.cpp: flex src/tokens.l
build out/parser.cpp: bison src/parser.y
build out/parser: cxx out/parser.cpp out/tokens.cpp src/codegen.cpp src/main.cpp

直接執行 ninja 預設會讀取 build.ninja 的設定:

$ ninja
[2/3] bison -d -o out/parser.cpp src/parser.y
src/parser.y: conflicts: 24 shift/reduce
[3/3] g++ -g -Iinclude -Iout -I/usr/local/include -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -fno-exceptions -fno-rt...nsformUtils -lLLVMipa -lLLVMAnalysis -lLLVMTarget -lLLVMMC -lLLVMCore -lLLVMSupport  -o out/parser out/parser.cpp out/tokens.cpp src/codegen.cpp src/main.cpp

安裝

在 Mac 上安裝用 Homebrew 可以輕鬆搞定:

$ brew install ninja

如果你的程式不大,source 檔案間的相依性很單純的話,通常直接撰寫 ninja 的 build 檔就行了。但對於中大型的程式,比較好的方式是搭配 high-level build system 例如 cmake 或是 gyp 來間接產生 build.ninja,有時甚至自己寫個 generator 更方便些,例如 TextMate 就是這樣做的

Ninja 的作者 Evan Martin 過去是個 Google Chrome 的開發者,應該是受不了 make 的龜速所以就創造了 Ninja 來拯救所有的 programmer 吧。

如果你習慣用 TextMate 做文字編輯,也有一個 bundle 可以做 ninja 語法的高亮。

2016-01-24 補充