在 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-srcrustup component add llvm-tools-preview二 命令行调试步骤
cargo build(生成于 target/debug/)cargo build --release(生成于 target/release/)rust-gdb target/debug/your_projectbreak main 或 break your_crate::your_functionrun(或 continue)next(不进入函数)、step(进入函数)print variable_namebacktracebreak your_function if variable_name == 42rust-lldb target/debug/your_projectbreakpoint set --name main 或 --name your_crate::your_functionrun / continuenext / stepframe variable 或 print variable_namebtRUST_BACKTRACE=1 cargo run 或 RUST_BACKTRACE=1 ./target/debug/your_project三 使用 VS Code 调试
{
"version": "0.2.0",
"configurations": [
{
"type": "cppdbg",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/target/debug/your_project_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"
}
]
}
cargo build 任务,并在 preLaunchTask 中引用。四 进阶工具与技巧
sudo apt install valgrind,运行:valgrind --tool=memcheck target/debug/your_programstrace -p <PID> 或 strace -e trace=open,read,write your_programltrace -p <PID> 或 ltrace your_programcargo install cargo-watch,运行:cargo watch -x run(文件变更自动构建并运行)五 常见问题与排查
cargo clean && cargo buildRUST_BACKTRACE=1 再运行;确保终端支持 UTF-8 输出