其他
Ninja 构建失败诊断、并行调优与 CMake 生成…
当使用 Ninja 作为 CMake 或其他元构建系统的底层执行器,需要排查失败、查看详细输出、调优并行、清理、生成 compile_commands.json 或理解 build.ninja 时使用。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 35/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 38/100 ×0.15
适用场景
Ninja 构建失败诊断、并行调优与 C特定
解决思路
- 用 Ninja 作为 CMake 生成器配置项目:`cmake -S . -B build -G Ninja`。
- 通过 CMake 调用 Ninja 构建:`cmake --build build`(内部使用 ninja)。
- 或直接进入构建目录调用 ninja:`cd build && ninja`。
- 指定并行任务数:`ninja -j4`。
- 按 CPU 核数指定并行任务数:`ninja -j$(nproc)`。
- 构建指定 target:`ninja myapp`。
- 执行安装 target:`ninja install`。
- 使用 Ninja Multi-Config:`cmake -S . -B build -G "Ninja Multi-Config"`。
- 在 Ninja Multi-Config 下构建 Release:`cmake --build build --config Release`。
- 在 Ninja Multi-Config 下构建 Debug:`cmake --build build --config Debug`。
- 显示完整命令而不是 `[CC] foo.c`:`ninja -v`。
- 干跑,显示将会构建什么:`ninja -n`。
- 显示某 target 为什么需要重建:`ninja -d explain myapp`。
- 打印所有 targets:`ninja -t targets all`。
- 按 rule 分组打印 targets:`ninja -t targets rule cc`。
- 生成依赖图(graphviz):`ninja -t graph myapp | dot -Tsvg -o deps.svg`。
- 使用 `-j N`:设置并行任务数(默认 CPUs + 2)。
- 使用 `-l N`:当 load average > N 时不启动新任务。
- 使用 `-k N`:在 N 个失败后继续(默认 1)。
- 使用 `-v`:verbose,显示完整命令行。
- 使用 `-n`:dry run。
- 使用 `-C dir`:执行任何操作前切换到 `dir`。
- 使用 `-t tool`:运行子工具(`clean`、`query`、`targets`、`graph`、`compdb`)。
- 清理构建输出:`ninja -t clean`。
- 同时清理生成文件:`ninja -t clean -g`。
- 或通过 CMake 清理:`cmake --build build --target clean`。
- 生成 compile_commands.json:`cmake -S . -B build -G Ninja -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`。
- 将 compile_commands.json 链接到项目根目录:`ln -sf build/compile_commands.json .`。
- 阅读/编写 build.ninja 变量:`cflags = -Wall -O2`。
- 阅读/编写 rule:`rule cc`、`command = gcc $cflags -c $in -o $out`、`description = CC $in`。
- 阅读/编写 build edge:`build foo.o: cc foo.c`。
- 阅读/编写 phony target:`build all: phony foo.o`。
- 阅读/编写 default target:`default all`。
- 理解 build.ninja 关键概念 `rule`:定义如何从输入产生输出。
- 理解 build.ninja 关键概念 `build`:用具体文件实例化 rule。
- 理解 build.ninja 关键概念 `$in` / `$out`:输入/输出的自动变量。
- 理解 build.ninja 关键概念 `phony`:总被认为过期的 target(类似 make 的 `.PHONY`)。
- 列出所有构建 targets:`ninja -t targets`。
- 查询某 target 的依赖:`ninja -t query myapp`。
- 清理:`ninja -t clean`。
- 如果 generator 支持,生成 compile_commands.json:`ninja -t compdb cc cxx > compile_commands.json`。
- 列出 rules:`ninja -t rules`。
- 遇到 `ninja: error: 'foo.o', needed by 'prog', missing and no known rule to make it`:原因是缺少构建规则;用 CMake 重新生成,并检查 `add_executable` 的源文件列表。
- 遇到构建未拾取变更:原因是 `build.ninja` 过期;重新运行 `cmake -S . -B build`。
- 遇到并行构建非常慢:原因是 `-j` 对 I/O 密集型构建过高;使用 `-l$(nproc)` 按负载限制。
- 遇到循环依赖:原因是 rule 依赖自身;检查 CMake target 依赖。
- 查阅完整 Ninja 命令参考、build.ninja 格式细节和 CMake 集成模式:见 `references/cheatsheet.md`。
适用边界 · 注意事项
- 不要用于基于 Make 的项目;应使用 `skills/build-systems/make`。
- 不要用于处理生成 Ninja 文件的 CMake 配置本身;应使用 `skills/build-systems/cmake`。
- `build.ninja` 很少手写,不要把它当作主要编辑对象;通常在调试时理解其格式即可。