关于 rustc-basics
面向使用 rustc 和 Cargo 的 Agent 的 Rust 编译技能,涵盖构建配置与参数、编译产物检查、单态化、二进制体积控制及常见错误排查。
主要功能
- 01配置 Cargo 构建配置
- 02使用 RUSTFLAGS 设置编译选项
- 03检查 MIR 和汇编
- 04了解单态化的影响
- 05缩减二进制体积
- 06排查常见编译错误
适用场景
- 01调整发布构建的速度或体积
- 02检查函数生成的汇编
- 03调查编译缓慢或二进制膨胀
- 04诊断 Rust 编译错误
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mohitmishra786/ low-level-dev-skills --skill rustc-basics安装后在 Claude Code 中输入/rustc-basics确认已加载。
附带文件references/rustflags-profiles.md
详细介绍
rustc 基础
用途
指导 Agent 调用 Rust 编译器:RUSTFLAGS、Cargo 配置文件中的构建配置、构建模式、MIR 和汇编检查、单态化,以及常见的编译错误模式。
触发条件
- “如何配置 Rust 发布构建以获得最佳性能?”
- “如何查看 Rust 函数的汇编输出?”
- “什么是单态化?为什么它会拖慢编译?”
- “如何在 Rust 中启用 LTO?”
- “我的 Rust 二进制文件太大了,如何缩小它?”
- “如何读取 Rust MIR 输出?”
工作流
1. 选择构建模式
# Debug (default) — fast compile, no optimization, debug info
cargo build
# Release — optimized, no debug info by default
cargo build --release
# Check only (fastest, no codegen)
cargo check
# Build for specific target
cargo build --release --target aarch64-unknown-linux-gnu
2. Cargo.toml 构建配置
[profile.release]
opt-level = 3 # 0-3, "s" (size), "z" (aggressive size)
debug = false # true = full, 1 = line tables only, 0 = none
lto = "thin" # false | "thin" | true (fat LTO)
codegen-units = 1 # 1 = max optimization, higher = faster compile
panic = "abort" # "unwind" (default) | "abort" (smaller binary)
strip = "symbols" # "none" | "debuginfo" | "symbols"
overflow-checks = false # default true in debug, false in release
[profile.release-with-debug]
inherits = "release"
debug = true # release build with debug symbols
strip = "none"
[profile.dev]
opt-level = 1 # Speed up debug builds slightly
| 设置 | 影响 |
|---|---|
lto = true(fat) | 优化效果最佳,链接速度最慢 |
lto = "thin" | 优化效果良好,可并行链接 |
codegen-units = 1 | 内联效果最佳,编译较慢 |
panic = "abort" | 移除展开表,减小二进制文件 |
opt-level = "z" | 大幅减小体积 |
3. RUSTFLAGS
# Set for a single build
RUSTFLAGS="-C target-cpu=native" cargo build --release
# Enable all target CPU features
RUSTFLAGS="-C target-cpu=native -C target-feature=+avx2,+bmi2" cargo build --release
# Control codegen at invocation level
RUSTFLAGS="-C opt-level=3 -C codegen-units=1 -C lto=on" cargo build --release
在 .cargo/config.toml 中持久设置:
[build]
rustflags = ["-C", "target-cpu=native"]
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "target-cpu=native", "-C", "link-arg=-fuse-ld=lld"]
4. 检查汇编输出
# Using cargo-show-asm (recommended)
cargo install cargo-show-asm
cargo asm --release 'myapp::module::function_name'
# Using rustc directly
rustc --emit=asm -C opt-level=3 -C target-cpu=native src/lib.rs
cat lib.s
# View MIR (mid-level IR, before codegen)
rustc --emit=mir -C opt-level=3 src/lib.rs
cat lib.mir
# View LLVM IR
rustc --emit=llvm-ir -C opt-level=3 src/lib.rs
cat lib.ll
# Use Compiler Explorer (Godbolt) patterns locally
RUSTFLAGS="--emit=asm" cargo build --release
find target/ -name "*.s"
5. 理解单态化
Rust 泛型会进行单态化——每种具体类型实例化都会生成独立代码。这会导致:
- 二进制文件体积膨胀
- 编译时间延长
- 可能增加 i-cache 压力
# Measure monomorphization bloat
cargo install cargo-llvm-lines
cargo llvm-lines --release | head -30
# Shows: lines of LLVM IR per function (monomorphized copies visible)
缓解策略:
// 1. Type erasure with dyn Trait (trades monomorphization for dispatch)
fn process(iter: &mut dyn Iterator<Item = i32>) { ... }
// 2. Non-generic inner function pattern
fn my_generic<T: AsRef<str>>(s: T) {
fn inner(s: &str) { /* actual work */ }
inner(s.as_ref()) // monomorphization only in thin wrapper
}
6. 减小二进制文件体积
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = "symbols"
# Check binary size breakdown
cargo install cargo-bloat
cargo bloat --release --crates # per-crate size
cargo bloat --release -n 20 # top 20 largest functions
# Compress executable (at cost of startup time)
upx --best --lzma target/release/myapp
7. 常见错误排查
| 错误 | 原因 | 修复方法 |
|---|---|---|
cannot find function in this scope | 缺少 use 或模块路径错误 | 添加 use crate::module::fn_name |
the trait X is not implemented for Y | 缺少 impl 或泛型约束错误 | 实现该 trait 或调整约束 |
lifetime may not live long enough | 借用检查器的生命周期问题 | 添加显式生命周期标注 |
cannot borrow as mutable because also borrowed as immutable | 别名违规 | 调整借用结构,避免借用重叠 |
use of moved value | 值被 move 到闭包或函数后再次使用 | 使用 .clone() 或改为借用 |
mismatched types: expected &str found String | 混淆了 String 和 &str | 使用 .as_str() 或 &my_string |
8. 实用的 rustc 标志
# Show all enabled features at a given opt level
rustc -C opt-level=3 --print cfg
# List available targets
rustc --print target-list
# Show target-specific features
rustc --print target-features --target x86_64-unknown-linux-gnu
# Explain an error code
rustc --explain E0382
RUSTFLAGS 参考和 Cargo 构建配置模式,请参阅 references/rustflags-profiles.md。
相关技能
- 使用
skills/rust/cargo-workflows管理工作区和使用 Cargo 工具 - 使用
skills/rust/rust-debugging通过 GDB/LLDB 调试 Rust 二进制文件 - 使用
skills/rust/rust-profiling进行性能分析并生成火焰图 - 使用
skills/rust/rust-sanitizers-miri验证内存安全
评论
支持 Markdown