附录 A:编译加速与安装疑难
Bevy 项目首次编译需要 5—15 分钟(取决于硬件),增量编译也要 10—30 秒。这是 Rust + 大型依赖树的固有开销,但可以通过以下手段显著缓解。
1. 链接器
默认的 link.exe(Windows MSVC)和 cc(Linux/macOS)链接速度慢。替换为更快的链接器:
Windows:lld-link
在 .cargo/config.toml 中配置:
toml
[target.x86_64-pc-windows-msvc]
linker = "rust-lld"Rust 自带 rust-lld,无需额外安装。
Linux/macOS:mold
mold 是目前最快的链接器:
console
# Ubuntu
sudo apt install mold
# macOS
brew install moldtoml
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=mold"]2. 动态链接
dynamic_linking feature 让 Bevy 以动态库形式链接,增量编译从 30 秒降到 3—5 秒:
toml
[dependencies]
bevy = { version = "=0.18.1", features = ["dynamic_linking"] }仅限开发期——发布时必须去掉,否则需要分发 .dll/.dylib/.so 文件。
3. 增量编译
Cargo 默认启用增量编译。确保没有禁用:
console
# 检查环境变量
echo $CARGO_INCREMENTAL # 应该为空或 1增量编译只重新编译变更的 crate 和它的下游依赖。
4. sccache / ccache
sccache 缓存编译结果,相同代码不重复编译:
console
cargo install sccachetoml
# .cargo/config.toml
[build]
rustc-wrapper = "sccache"对 CI 构建尤其有效——多次构建相同代码时命中缓存。
5. 编译 profile 优化
toml
[profile.dev]
opt-level = 1 # 自身代码 O1,保留调试能力
[profile.dev.package."*"]
opt-level = 3 # 依赖 O3,运行时不慢这是 Bevy 官方推荐的开发期配置。
6. 减少依赖
检查 cargo tree 看依赖树。不必要的 feature 会增加编译时间:
toml
# 只用你需要的功能
bevy = { version = "=0.18.1", default-features = false, features = ["bevy_render", "bevy_sprite"] }7. 常见安装问题
| 问题 | 解决方案 |
|---|---|
| Windows 缺少 C++ 构建工具 | 安装 Visual Studio Build Tools,勾选"使用 C++ 的桌面开发" |
| Linux 缺少图形库 | sudo apt install libudev-dev libasound2-dev libwayland-dev |
| macOS Xcode 版本过低 | 更新 Xcode 到最新版本 |
| 首次编译 OOM | 减少并行编译数:cargo build -j 4 |
| wasm32 目标缺失 | rustup target add wasm32-unknown-unknown |
8. 编译时间参考
| 配置 | 首次全量编译 | 增量编译 |
|---|---|---|
| 默认配置 | 10—15 分钟 | 20—40 秒 |
| lld/mold + 动态链接 + sccache | 8—12 分钟 | 3—8 秒 |
| 全量 LTO release | 15—30 分钟 | 15—30 分钟 |