rustc-basics
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineserustc Basics
rustc 基础
Purpose
用途
Guide agents through Rust compiler invocation: RUSTFLAGS, Cargo profile configuration, build modes, MIR and assembly inspection, monomorphization, and common compilation error patterns.
指导开发者完成Rust编译器的调用操作:包括RUSTFLAGS设置、Cargo配置文件配置、构建模式选择、MIR与汇编查看、单态化理解,以及常见编译错误排查。
Triggers
触发场景
- "How do I configure a release build in Rust for maximum performance?"
- "How do I see the assembly output for a Rust function?"
- "What is monomorphization and why is it making my compile slow?"
- "How do I enable LTO in Rust?"
- "My Rust binary is too large — how do I shrink it?"
- "How do I read Rust MIR output?"
- "如何在Rust中配置发布构建以获得最佳性能?"
- "如何查看Rust函数的汇编输出?"
- "什么是单态化,为什么它会导致编译变慢?"
- "如何在Rust中启用LTO?"
- "我的Rust二进制文件太大了——如何缩小它?"
- "如何读取Rust的MIR输出?"
Workflow
操作流程
1. Choose a build mode
1. 选择构建模式
bash
undefinedbash
undefinedDebug (default) — fast compile, no optimization, debug info
Debug (default) — fast compile, no optimization, debug info
cargo build
cargo build
Release — optimized, no debug info by default
Release — optimized, no debug info by default
cargo build --release
cargo build --release
Check only (fastest, no codegen)
Check only (fastest, no codegen)
cargo check
cargo check
Build for specific target
Build for specific target
cargo build --release --target aarch64-unknown-linux-gnu
undefinedcargo build --release --target aarch64-unknown-linux-gnu
undefined2. Cargo.toml profile configuration
2. Cargo.toml配置文件配置
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| Setting | Impact |
|---|---|
| Best optimization, slowest link |
| Good optimization, parallel link |
| Best inlining, slower compile |
| Removes unwind tables, smaller binary |
| Aggressive size reduction |
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| 设置项 | 影响 |
|---|---|
| 最优优化效果,链接速度最慢 |
| 良好优化效果,支持并行链接 |
| 最佳内联效果,编译速度更慢 |
| 移除 unwind 表,生成更小的二进制文件 |
| 激进的体积缩减优化 |
3. RUSTFLAGS
3. RUSTFLAGS设置
bash
undefinedbash
undefinedSet for a single build
Set for a single build
RUSTFLAGS="-C target-cpu=native" cargo build --release
RUSTFLAGS="-C target-cpu=native" cargo build --release
Enable all target CPU features
Enable all target CPU features
RUSTFLAGS="-C target-cpu=native -C target-feature=+avx2,+bmi2" cargo build --release
RUSTFLAGS="-C target-cpu=native -C target-feature=+avx2,+bmi2" cargo build --release
Control codegen at invocation level
Control codegen at invocation level
RUSTFLAGS="-C opt-level=3 -C codegen-units=1 -C lto=on" cargo build --release
Persistent in `.cargo/config.toml`:
```toml
[build]
rustflags = ["-C", "target-cpu=native"]
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "target-cpu=native", "-C", "link-arg=-fuse-ld=lld"]RUSTFLAGS="-C opt-level=3 -C codegen-units=1 -C lto=on" cargo build --release
在 `.cargo/config.toml` 中持久化配置:
```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. Inspect assembly output
4. 查看汇编输出
bash
undefinedbash
undefinedUsing cargo-show-asm (recommended)
Using cargo-show-asm (recommended)
cargo install cargo-show-asm
cargo asm --release 'myapp::module::function_name'
cargo install cargo-show-asm
cargo asm --release 'myapp::module::function_name'
Using rustc directly
Using rustc directly
rustc --emit=asm -C opt-level=3 -C target-cpu=native src/lib.rs
cat lib.s
rustc --emit=asm -C opt-level=3 -C target-cpu=native src/lib.rs
cat lib.s
View MIR (mid-level IR, before codegen)
View MIR (mid-level IR, before codegen)
rustc --emit=mir -C opt-level=3 src/lib.rs
cat lib.mir
rustc --emit=mir -C opt-level=3 src/lib.rs
cat lib.mir
View LLVM IR
View LLVM IR
rustc --emit=llvm-ir -C opt-level=3 src/lib.rs
cat lib.ll
rustc --emit=llvm-ir -C opt-level=3 src/lib.rs
cat lib.ll
Use Compiler Explorer (Godbolt) patterns locally
Use Compiler Explorer (Godbolt) patterns locally
RUSTFLAGS="--emit=asm" cargo build --release
find target/ -name "*.s"
undefinedRUSTFLAGS="--emit=asm" cargo build --release
find target/ -name "*.s"
undefined5. Understand monomorphization
5. 理解单态化
Rust generics are monomorphized — each concrete type instantiation produces separate code. This causes:
- Binary size bloat
- Longer compile times
- Potential i-cache pressure
bash
undefinedRust泛型采用单态化实现——每种具体类型的实例化都会生成独立的代码。这会导致:
- 二进制文件体积膨胀
- 编译时间延长
- 潜在的指令缓存压力
bash
undefinedMeasure monomorphization bloat
Measure monomorphization bloat
cargo install cargo-llvm-lines
cargo llvm-lines --release | head -30
cargo install cargo-llvm-lines
cargo llvm-lines --release | head -30
Shows: lines of LLVM IR per function (monomorphized copies visible)
Shows: lines of LLVM IR per function (monomorphized copies visible)
Mitigation strategies:
```rust
// 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
}
缓解策略:
```rust
// 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. Binary size reduction
6. 二进制文件体积缩减
toml
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = "symbols"bash
undefinedtoml
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = "symbols"bash
undefinedCheck binary size breakdown
Check binary size breakdown
cargo install cargo-bloat
cargo bloat --release --crates # per-crate size
cargo bloat --release -n 20 # top 20 largest functions
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)
Compress executable (at cost of startup time)
upx --best --lzma target/release/myapp
undefinedupx --best --lzma target/release/myapp
undefined7. Common error triage
7. 常见错误排查
| Error | Cause | Fix |
|---|---|---|
| Missing | Add |
| Missing impl or wrong generic bound | Implement trait or adjust bounds |
| Borrow checker lifetime issue | Add explicit lifetime annotations |
| Aliasing violation | Restructure borrows to not overlap |
| Value used after | Use |
| String vs &str confusion | Use |
| 错误 | 原因 | 修复方案 |
|---|---|---|
| 缺少 | 添加 |
| 缺少 trait 实现或泛型约束错误 | 实现对应的 trait 或调整泛型约束 |
| 借用检查器的生命周期问题 | 添加显式的生命周期注解 |
| 违反别名规则 | 重构代码避免借用重叠 |
| 值被移动到闭包或函数后再次使用 | 使用 |
| String与&str混淆 | 使用 |
8. Useful rustc flags
8. 实用rustc标志
bash
undefinedbash
undefinedShow all enabled features at a given opt level
Show all enabled features at a given opt level
rustc -C opt-level=3 --print cfg
rustc -C opt-level=3 --print cfg
List available targets
List available targets
rustc --print target-list
rustc --print target-list
Show target-specific features
Show target-specific features
rustc --print target-features --target x86_64-unknown-linux-gnu
rustc --print target-features --target x86_64-unknown-linux-gnu
Explain an error code
Explain an error code
rustc --explain E0382
For RUSTFLAGS reference and Cargo profile patterns, see [references/rustflags-profiles.md](references/rustflags-profiles.md).rustc --explain E0382
关于RUSTFLAGS参考和Cargo配置文件模式,可查看[references/rustflags-profiles.md](references/rustflags-profiles.md)。Related skills
相关技能
- Use for workspace management and Cargo tooling
skills/rust/cargo-workflows - Use for debugging Rust binaries with GDB/LLDB
skills/rust/rust-debugging - Use for profiling and flamegraphs
skills/rust/rust-profiling - Use for memory safety validation
skills/rust/rust-sanitizers-miri
- 如需工作区管理和Cargo工具使用,可使用
skills/rust/cargo-workflows - 如需使用GDB/LLDB调试Rust二进制文件,可使用
skills/rust/rust-debugging - 如需性能分析和火焰图生成,可使用
skills/rust/rust-profiling - 如需内存安全验证,可使用
skills/rust/rust-sanitizers-miri