在 Linux 下调试 Rust 程序,常见、好用的方法主要有以下几类,从入门到进阶给你梳理一下。
Rust 编译出的就是普通 ELF 二进制,可以直接用 C/C++ 调试器。
cargo build # 或
cargo build --debug
默认就是 debug 模式,包含符号信息
安装调试器:
# Ubuntu / Debian
sudo apt install gdb
# 想用 lldb
sudo apt install lldb
gdb target/debug/your_program
常用命令:
run
break main
break src/main.rs:20
next
step
print x
backtrace
⚠️ Rust 的变量名可能被 mangled,可读性一般。
rust-gdb target/debug/your_program
或:
rust-lldb target/debug/your_program
它们会:
String, Vec, Option 等launch.json{
"type": "lldb",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/target/debug/your_program",
"args": [],
"cwd": "${workspaceFolder}"
}
然后:
✅ 这是最舒服的 Rust 调试方式
println!println!("x = {:?}", x);
log + env_logger[dependencies]
log = "0.4"
env_logger = "0.11"
use log::{info, warn};
fn main() {
env_logger::init();
info!("starting");
}
运行:
RUST_LOG=debug cargo run
RUST_BACKTRACE=1 cargo run
或:
RUST_BACKTRACE=full cargo run
如果是 tokio:
[dependencies]
tokio = { version = "1", features = ["full"] }
调试技巧:
tokio-console| 场景 | 推荐方式 |
|---|---|
| 新手 | println! + RUST_BACKTRACE |
| 逻辑错误 | VS Code + LLDB |
| 崩溃 | GDB / backtrace |
| 并发问题 | 日志 + sanitizer |
| 性能 | perf, flamegraph |
cargo flamegraphvalgrindsanitizer:RUSTFLAGS="-Z sanitizer=address" cargo run
如果你愿意,可以告诉我:
我可以给你更具体的配置示例。