在 Debian 上调试 Rust 的实用指南
一 环境准备
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource $HOME/.cargo/envsudo apt update && sudo apt install gdb lldbrustup component add rust-src llvm-tools-previewcargo build 或 cargo run。二 使用 GDB 或 LLDB 命令行调试
rust-gdb target/debug/your_programrust-lldb target/debug/your_programbreak main 或 break your_crate::your_functioncontinuestep / nextprint variable_namebacktrace(缩写 bt)break your_function if variable_name == 42RUST_BACKTRACE=1 cargo runRUST_BACKTRACE=1 ./target/debug/your_programgdb -p <PID> 附加。三 使用 VS Code 进行图形化调试
.vscode/launch.json(示例,使用 GDB):
your_program_name 替换为实际二进制名(Cargo 默认与 crate 同名){
"version": "0.2.0",
"configurations": [
{
"type": "cppdbg",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/target/debug/your_program_name",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "cargo build"
}
]
}
.vscode/tasks.json 的 cargo build 任务(label 与 preLaunchTask 一致)。四 辅助工具与技巧
println!("{:?}", value)、println!("{:#?}", value)(需 #[derive(Debug)])dbg!(value) 快速输出值与位置log + env_logger 并运行:RUST_LOG=info cargo runstrace -p <PID> 或 strace -e trace=open,read,write -p <PID>ltrace -p <PID>sudo apt install valgrind,运行:valgrind --tool=memcheck target/debug/your_programcargo install cargo-watchcargo watch -x runCargo.toml 的 [profile.dev] 中使用标准库分配器进行对比排查。五 打包与发布时的调试符号处理
gdb/lldb 分析:
Cargo.toml 中启用 release 调试信息[profile.release]
debug = true
cargo install cargo-debcargo deb --separate-debug-symbolscargo deb 打包的二进制会剥离调试符号,分离后更易在调试环境中使用。