用途:这是一份 Rust 编译器(rustc)使用技能,面向系统编程场景,指导代理完成编译器调用、构建配置、产物分析与错误排查。
主要能力与使用方式: 构建模式:cargo build(调试,快编译无优化)、cargo build --release(优化)、cargo check(仅检查,最快)、cargo build --release --target aarch64-unknown-linux-gnu(指定目标)。 Cargo.toml profile 配置:在 [profile.release] 中设置 opt-level、debug、lto、codegen-units、panic、strip、overflow-checks 等;可用 inherits 派生自定义 profile。资料给出各项影响,例如 lto=true(fat)优化最好但链接最慢,thin 支持并行链接,codegen-units=1 内联最佳但编译更慢,panic="abort" 去掉 unwind 表以减小体积,opt-level="z" 激进减体积。 RUSTFLAGS:单次构建可写 RUSTFLAGS="-C target-cpu=native" cargo build --release,也可组合 target-feature、opt-level、codegen-units、lto;持久化写入 .cargo/config.toml 的 [build] 或 [target.x86_64-unknown-linux-gnu] 段。 产物检查:cargo install cargo-show-asm 后使用 cargo asm --release 'myapp::module::function_name';或 rustc --emit=asm/--emit=mir/--emit=llvm-ir 生成 .s、.mir、.ll 文件查看。 单态化:Rust 泛型按具体类型实例化代码,导致体积膨胀、编译变慢、i-cache 压力;可用 cargo-llvm-lines 统计(cargo llvm-lines --release),缓解手段包括 dyn Trait 类型擦除和非泛型内部函数模式。 体积缩减:设置 opt-level="z"、lto=true、codegen-units=1、panic="abort"、strip="symbols";用 cargo-bloat 查看体积分布(--crates 或 -n 20);可用 upx 压缩(代价是启动时间)。 错误排查:资料列出常见错误及成因/修复,如 cannot find function in this scope(缺少 use)、trait not implemented、生命周期、可变/不可变借用冲突、use of moved value、&str 与 String 不匹配等。 实用 rustc 旗标:rustc -C opt-level=3 --print cfg、rustc --print target-list、rustc --print target-features、rustc --explain E0382。
适用场景:release 构建性能调优、查看汇编/MIR/LLVM IR、减小二进制体积、排查编译错误。关联技能包括 cargo-workflows、rust-debugging、rust-profiling、rust-sanitizers-miri。限制:仅覆盖 rustc 与 Cargo 构建层面,其他细节暂未提供。