温馨提示×

linux怎么调试rust

小樊
54
2026-10-18 19:32:18
栏目: 编程语言

在 Linux 上调试 Rust 程序,常见方式有以下几种,从最常用到进阶逐步说明。


一、使用 GDB / LLDB 调试(推荐)

Rust 编译出的就是原生二进制,完全可以用 C/C++ 调试器调试。

1. 编译时保留调试信息

cargo build
# 或
cargo build --debug

默认 debug 模式已包含调试符号。

如果是 release:

cargo build --release

可在 Cargo.toml 中加:

[profile.release]
debug = true

2. 安装调试器

GDB(最常用)

sudo apt install gdb

LLDB(mac / clang 系更友好)

sudo apt install lldb

3. 用 GDB 调试

gdb target/debug/your_program

常用命令:

run
break main
break src/main.rs:10
next
step
print x
backtrace
quit

⚠️ Rust 名字会被 mangled,可加:

set rust on

4. 用 LLDB(推荐对 Rust 更友好)

lldb target/debug/your_program
break set -f main.rs -l 10
run
bt

二、使用 VSCode 图形化调试(最推荐)

1. 安装

  • Rust Analyzer
  • CodeLLDB(或 C/C++)

2. 配置 .vscode/launch.json

示例(LLDB):

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "lldb",
      "request": "launch",
      "name": "Debug",
      "program": "${workspaceFolder}/target/debug/your_program",
      "args": [],
      "cwd": "${workspaceFolder}"
    }
  ]
}

然后:

  • 打 breakpoint
  • F5 启动

✅ 变量、stack、async 都支持得很好


三、打印调试(最快)

1. println!

println!("x = {:?}", x);

2. dbg!(强烈推荐)

let x = dbg!(some_func());

会打印:

  • 文件
  • 行号
  • 值

四、日志调试(生产环境)

使用 log + env_logger

[dependencies]
log = "0.4"
env_logger = "0.11"
fn main() {
    env_logger::init();
    log::info!("start");
}

运行:

RUST_LOG=debug ./target/debug/your_program

五、检查崩溃 / Panic

1. Backtrace

RUST_BACKTRACE=1 cargo run

2. AddressSanitizer(内存错误)

cargo clean
RUSTFLAGS="-Z sanitizer=address" cargo run --target x86_64-unknown-linux-gnu

(需 nightly)


六、常用调试组合(推荐)

场景 工具
学习 / 小项目 dbg!
逻辑错误 VSCode + LLDB
崩溃 RUST_BACKTRACE=1
内存问题 AddressSanitizer
多线程 gdb + bt

如果你愿意,可以告诉我:

  • 是 命令行还是 GUI
  • 是否 多线程 / async
  • 是 学习还是线上问题

我可以给你更精确的调试方案。

0 踩