ST-Link在Linux远程STM32交叉编译项目中调试GDB

Keil跟linux下使用GDB调试器区别

ST-Link 硬件(ST-Link V2/V3)本身只是一个 JTAG/SWD 接口工具,它不包含 烧录功能、GDB 调试功能。

Windows 上的 Keil/IAR 封装了 烧录固件的程序跟GDB 相关调试功能,所以在 Keil 里可以直接调试,但底层仍然需要 ST-Link 驱动+调试协议。

而linux中是需要安装烧录工具跟GDB调试工具的

linux中搭建GDB调试环境

ST-Link 本质上是一个 调试/编程工具,但它本身 不是 GDB 调试器。它通常与 GDB 服务器(如 OpenOCDST-Link GDB Server)配合使用,以便 GDB 远程连接到目标 MCU 进行调试。

1. 确保工具链安装

在你的 Linux 服务器上,需要安装:

  • ARM 交叉编译工具链(gcc-arm-none-eabi

  • ST-Link 工具

    sudo apt install stlink-tools
    
  • GDB 调试服务器(OpenOCDST-Link GDB Server

    sudo apt install openocd
    
  • GDB 调试客户端(arm-none-eabi-gdb

    sudo apt install gdb-multiarch  # 或使用 arm-none-eabi-gdb
    

2. 在 Linux 服务器上启动 GDB 服务器

如果你使用 OpenOCD

openocd -f interface/stlink.cfg -f target/stm32f4x.cfg

或者如果是 ST-Link GDB Server

st-util

启动后,默认监听端口 3333(OpenOCD)或 4242(st-util)。


3. 在 VS Code 配置 GDB 远程调试

确保你在 VS Code 本地 安装了:

  • Remote-SSH 插件(用于连接 Linux 服务器)
  • Cortex-Debug 插件(支持 ARM 交叉调试)

在你的 STM32 项目目录下创建 .vscode/launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Remote Debug STM32",
            "type": "cppdbg",
            "request": "attach",
            "program": "${workspaceFolder}/build/my_firmware.elf",
            "miDebuggerServerAddress": "localhost:3333",
            "miDebuggerPath": "/usr/bin/arm-none-eabi-gdb",
            "setupCommands": [
                { "text": "target remote localhost:3333" },
                { "text": "monitor reset init" },
                { "text": "monitor halt" },
                { "text": "load" }
            ],
            "logging": {
                "trace": true,
                "traceResponse": true,
                "engineLogging": true
            }
        }
    ]
}

注意

  • program 需要指向你的 ELF 文件
  • miDebuggerServerAddress 需要与 GDB 服务器端口一致

4. 使用 GDB watch 变量

在 VS Code Debug ConsoleGDB 交互界面

  1. 进入调试模式后,设置断点

  2. 运行

    watch
    

    变量:

    watch my_variable
    
  3. 如果

    my_variable
    

    是局部变量,需要display

    display my_variable
    

5. 其他 GDB 调试命令

命令 作用
b main main() 处打断点
c 继续运行
n 单步执行(不进入函数)
s 单步执行(进入函数)
p var 打印变量 var
info locals 查看所有局部变量
watch var 监视变量 var 变化
delete 1 删除编号为 1 的断点
Logo

智能硬件社区聚焦AI智能硬件技术生态,汇聚嵌入式AI、物联网硬件开发者,打造交流分享平台,同步全国赛事资讯、开展 OPC 核心人才招募,助力技术落地与开发者成长。

更多推荐