Skip to content

16 WSL2 + Ubuntu 24.04 嵌入式开发环境搭建实战 · 主方案(261020) ​

本文记录从零开始在 Windows 上搭建 WSL2 + Ubuntu 24.04 + ARM/RISC-V 交叉工具链 + GDB + CMake/Make + OpenOCD + VS Code 的完整过程。 原则:每一步都有命令,每一步都有验证。 已验证环境:Windows 11 家庭版 25H2 + WSL 2.6.3.0 + Ubuntu 24.04.5 LTS + VS Code Remote-WSL。


0. 环境总览 ​

Windows 11 主机PowerShell(wsl 命令)· 文件资源管理器访问 \\wsl.localhost\Ubuntu-24.04WSL2 轻量虚拟机WSL 2.6.3.0 · 内核 6.6.87.2 · networkingMode=mirroredUbuntu 24.04.5 LTSARM GCC 13.2.1arm-none-eabi-gccRISC-V GCC 13.2.0riscv64-unknown-elf-gccGDB Multiarch 15.1gdb-multiarch 调试CMake 3.28 · Make 4.3OpenOCD 0.12.0 源码编译VS Code + Remote-WSL远程开发:WSL: Ubuntu-24.04左下角状态标识连接成功usbipd-win 5.3USB 透传:ST-Link / J-LinkCMSIS-DAP 调试器接入 WSL主方案:代码放 /home/user/projects,编译性能最好;两套环境(WSL / MSYS2)互相独立,不要混用
图 1 · WSL2 嵌入式开发环境整体链路:Windows 主机 → WSL2 虚拟机 → Ubuntu 24.04 工具链栈
组件版本 / 路径验证命令
WindowsWindows 11 家庭版 25H2 (26200.9445)winver
WSL2.6.3.0,内核 6.6.87.2-1wsl --version
Linux 发行版Ubuntu-24.04(WSL 里的名字)wsl --list --verbose
系统版本Ubuntu 24.04.5 LTScat /etc/os-release
用户名自定义(本文用 user)whoami
项目路径/home/user/projectspwd
镜像源华为云 mirrors.huaweicloud.comcat /etc/apt/sources.list.d/ubuntu.sources
ARM GCC13.2.1arm-none-eabi-gcc --version
RISC-V GCC13.2.0riscv64-unknown-elf-gcc --version
GDB Multiarch15.1gdb-multiarch --version
CMake3.28.3cmake --version
Make4.3make --version
OpenOCD0.12.0+dev-02684-g54a33aeabopenocd --version
OpenOCD 路径/usr/local/bin/openocdwhich openocd

整体链路:

text
Windows 11
  └─ WSL2 (2.6.3.0)
       └─ Ubuntu 24.04 LTS (WSL 发行版名: Ubuntu-24.04)
            └─ VS Code Remote-WSL
                 └─ ARM / RISC-V / CMake / Make / OpenOCD

1. Windows 侧:安装 WSL2 与 Ubuntu 24.04 ​

1.1 检查 Windows 版本 ​

powershell
winver

✅ 验证:弹出窗口显示 Windows 11,版本 25H2 (26200.9445) 或更高。

1.2 安装 WSL 和 Ubuntu ​

以管理员身份打开 PowerShell:

powershell
wsl --install -d Ubuntu-24.04

如果提示需要重启,重启后继续。

✅ 验证:

powershell
wsl --status
wsl --version

预期:显示 WSL 版本 2.x,默认版本 2。

1.3 确认 Ubuntu 是 WSL2 ​

powershell
wsl --list --verbose

预期:

text
  NAME            STATE           VERSION
* Ubuntu-24.04    Running         2

如果 VERSION 是 1:

powershell
wsl --set-version Ubuntu-24.04 2

1.4 首次进入并创建用户 ​

powershell
wsl -d Ubuntu-24.04

首次会提示创建 UNIX 用户和密码。本文使用:

  • 用户名:user(自定义即可)
  • 密码:自己设一个记得住的

✅ 验证:

bash
whoami                 # 输出: user
pwd                    # 输出: /home/user
cat /etc/os-release    # 显示 Ubuntu 24.04.x LTS

2. 网络问题排查与换源(关键步骤) ​

12345备份源文件cp ubuntu.sourcesubuntu.sources.bak换华为云源sed 替换mirrors.huaweicloud.com强制 IPv4Acquire::ForceIPv4规避 IPv6 路由不通修复 DNS8.8.8.8 / 223.5.5.5防 VS Code 1006 错误apt update 验证15~30 秒完成无大量 Err⚠ 踩坑记录.wslconfig 关键项:networkingMode=mirrored · dnsTunneling=true · autoProxy=true(autoProxy=false 会导致 WSL 虚拟网卡不初始化,ip addr 只有 lo)
图 2 · 换源与网络修复五步流程(每步均有验证命令)

2.1 启动 WSL 时的网络警告 ​

启动时提示:

text
wsl: 无法配置网络 (networkingMode Nat),回退到 networkingMode VirtioProxy。

这是 WSL 内部网络回退,不影响基本使用。后续 apt 源选择和 VS Code 远程连接需注意。

2.2 备份并更换镜像源 ​

国内直连 Ubuntu 官方源经常超时,需换国内源。实测华为云源稳定可用。

bash
# 备份
sudo cp /etc/apt/sources.list.d/ubuntu.sources /etc/apt/sources.list.d/ubuntu.sources.bak

# 换华为云源
sudo sed -i 's/archive.ubuntu.com/mirrors.huaweicloud.com/g' /etc/apt/sources.list.d/ubuntu.sources
sudo sed -i 's/security.ubuntu.com/mirrors.huaweicloud.com/g' /etc/apt/sources.list.d/ubuntu.sources

✅ 验证:

bash
cat /etc/apt/sources.list.d/ubuntu.sources | grep URIs

预期:输出中包含 mirrors.huaweicloud.com,不再有 archive.ubuntu.com。

⚠️ 踩坑记录:

  • 阿里云源:大文件下载易超时(ARM 工具链 600MB+ 时失败)
  • 清华源:某些 IP 连接超时
  • 华为云源:实测稳定,ARM 工具链 639MB 下载成功

2.3 强制 IPv4 ​

WSL 中 IPv6 经常路由不通,强制 APT 走 IPv4:

bash
echo 'Acquire::ForceIPv4 "true";' | sudo tee /etc/apt/apt.conf.d/99force-ipv4

✅ 验证:

bash
cat /etc/apt/apt.conf.d/99force-ipv4

预期:Acquire::ForceIPv4 "true";

2.4 更新软件源 ​

bash
sudo apt update

✅ 验证:应在 15–30 秒内完成,末尾显示 All packages are up to date. 或包列表,无大量 Err。

2.5 DNS 永久修复(防止 VS Code 1006 错误) ​

WSL 的 DNS 解析不稳定会导致 VS Code Server 下载失败或远程连接断开。

在 WSL 终端执行:

bash
sudo rm -f /etc/resolv.conf
sudo bash -c 'echo "nameserver 8.8.8.8" > /etc/resolv.conf'
sudo bash -c 'echo "nameserver 223.5.5.5" >> /etc/resolv.conf'
sudo chattr +i /etc/resolv.conf

✅ 验证:

bash
cat /etc/resolv.conf
ping -c 3 update.code.visualstudio.com

预期:能看到正常 ping 响应,不再报 Temporary failure in name resolution。

⚠️ 修正:chattr +i /etc/resolv.conf 在 WSL2 中不生效,报错 Operation not supported。
WSL2 的 /etc 位于虚拟磁盘,不支持 chattr。
正确做法是确保 .wslconfig 中 autoProxy=true,让 WSL 自动管理 DNS。
详见第 11.8 节。


3. 安装基础工具 ​

bash
sudo apt install -y curl wget git build-essential cmake make

✅ 验证:

bash
git --version
gcc --version
cmake --version
make --version

预期:

  • git 2.43.0(或更高)
  • gcc 13.3.0
  • cmake 3.28.3
  • make 4.3

4. 安装 ARM 工具链 ​

bash
sudo apt install -y gcc-arm-none-eabi gdb-multiarch

包大小约 590MB,需要几分钟。如果中断,重新执行同一条命令即可。

✅ 验证:

bash
arm-none-eabi-gcc --version | head -n 1
gdb-multiarch --version | head -n 1

预期:

  • arm-none-eabi-gcc (15:13.2.rel1-2) 13.2.1 20231009
  • GNU gdb (Ubuntu 15.1-1ubuntu1~24.04.1) 15.1

5. 安装 RISC-V 工具链 ​

bash
sudo apt install -y gcc-riscv64-unknown-elf

✅ 验证:

bash
riscv64-unknown-elf-gcc --version | head -n 1

预期:riscv64-unknown-elf-gcc (13.2.0-11ubuntu1+12) 13.2.0


6. 确认 gdb-multiarch 支持 ARM / RISC-V ​

bash
gdb-multiarch -ex "set architecture" -ex quit

✅ 验证:输出中应包含 arm、riscv、riscv:rv64、riscv:rv32。


7. 安装 OpenOCD 依赖 ​

bash
sudo apt install -y automake autoconf libtool pkg-config \
  libusb-1.0-0-dev libhidapi-dev libftdi1-dev texinfo

7.1 jimtcl(不需要手动编译) ​

Ubuntu 24.04 仓库中已有 libjim-dev:

bash
sudo apt install -y libjim-dev

✅ 验证:

bash
dpkg -l | grep libjim

预期:

text
ii  libjim-dev:amd64    0.82-4.1build2   ...
ii  libjim0.82t64:amd64 0.82-4.1build2   ...
bash
sudo apt install -y libjaylink-dev

✅ 验证:

bash
dpkg -l | grep libjaylink

预期:

text
ii  libjaylink-dev:amd64  0.3.1-1  ...
ii  libjaylink0:amd64     0.3.1-1  ...

⚠️ 踩坑记录:如果不装 libjaylink-dev,configure 阶段会报错: configure: error: libjaylink-0.2 is required for adapter_driver "SEGER J-Link Programmer".


8. 编译安装 OpenOCD ​

8.1 获取源码 ​

bash
cd ~
git clone https://github.com/openocd-org/openocd.git
cd openocd
./bootstrap

✅ 验证:./bootstrap 末尾输出 Bootstrap complete.

8.2 配置 ​

bash
./configure --enable-jlink --enable-stlink --enable-cmsis-dap \
  --enable-kitprog --enable-usb-blaster-2 --enable-ftdi \
  --enable-sysfsgpio --enable-bcm2835gpio

✅ 验证:末尾出现 OpenOCD configuration summary,需要的驱动为 yes:

text
MPSSE mode of FTDI based devices                 yes
ST-Link Programmer                               yes
CMSIS-DAP v1 compliant dongle (HID)              yes
Cypress KitProg Programmer                       yes
Altera USB-Blaster II Compatible                 yes
Linux GPIO bitbang through sysfs                 yes
SEGGER J-Link Programmer                         yes
Bitbanging on BCM2835 (as found in Raspberry Pi) yes

8.3 编译并安装 ​

bash
make -j$(nproc)
sudo make install
sudo ldconfig

✅ 验证:

bash
openocd --version
which openocd

预期:

  • Open On-Chip Debugger 0.12.0+dev-02684-g54a33aeab ...
  • /usr/local/bin/openocd

9. 一键验收(所有工具链) ​

bash
echo "===== OS ====="
cat /etc/os-release | head -n 2

echo "===== ARM GCC ====="
arm-none-eabi-gcc --version | head -n 1

echo "===== RISC-V GCC ====="
riscv64-unknown-elf-gcc --version | head -n 1

echo "===== GDB Multiarch ====="
gdb-multiarch --version | head -n 1

echo "===== CMake ====="
cmake --version | head -n 1

echo "===== Make ====="
make --version | head -n 1

echo "===== OpenOCD ====="
openocd --version | head -n 1

echo "===== OpenOCD Path ====="
which openocd

✅ 本次验证结果(全部通过):

text
===== OS =====
PRETTY_NAME="Ubuntu 24.04.5 LTS"
NAME="Ubuntu"
===== ARM GCC =====
arm-none-eabi-gcc (15:13.2.rel1-2) 13.2.1 20231009
===== RISC-V GCC =====
riscv64-unknown-elf-gcc (13.2.0-11ubuntu1+12) 13.2.0
===== GDB Multiarch =====
GNU gdb (Ubuntu 15.1-1ubuntu1~24.04.1) 15.1
===== CMake =====
cmake version 3.28.3
===== Make =====
GNU Make 4.3
===== OpenOCD =====
Open On-Chip Debugger 0.12.0+dev-02684-g54a33aeab (2026-09-14-04:59)
===== OpenOCD Path =====
/usr/local/bin/openocd

10. VS Code 连接 WSL ​

10.1 安装 WSL 扩展 ​

在 VS Code 扩展市场安装 WSL 扩展。

10.2 连接 WSL ​

  1. 按 Ctrl + Shift + P。
  2. 输入 WSL: Connect to WSL。
  3. 选择 Ubuntu-24.04。

✅ 验证:

  • VS Code 左下角显示 WSL: Ubuntu-24.04。
  • 终端提示符为 user@ubuntu:~/projects$。

10.3 从 WSL 终端启动 VS Code(推荐) ​

bash
cd ~/projects
code .

✅ 验证:VS Code 打开,左下角显示 WSL: Ubuntu-24.04,资源管理器里能看到 /home/user/projects 下的文件。

10.4 Windows 文件资源管理器访问 Linux 文件 ​

地址栏输入:

text
\\wsl.localhost\Ubuntu-24.04

或旧路径:

text
\\wsl$\Ubuntu-24.04

✅ 验证:能看到 /home、/etc、/usr 等根目录。

注意:

  • 这不是 Windows 给 Linux 单独分了一个磁盘分区,而是 WSL 虚拟磁盘入口。
  • 不要在 Windows 里直接修改 Linux 根文件系统,容易权限错乱。
  • 代码项目统一放 /home/user/projects,编译性能最好。
  • Windows 的 C 盘在 WSL 里是 /mnt/c。

11. 常见错误与修复 ​

11.1 VS Code 报 WebSocket close with status code 1006 ​

现象:

text
无法获取远程环境
无法连接到远程扩展主机服务器 (错误: WebSocket close with status code 1006)

原因:WSL 网络模式回退到 VirtioProxy 或 DNS 解析失败,导致下载 VS Code Server 失败。

解决方案(手动安装 VS Code Server):

  1. 在 Windows 浏览器下载对应 commit 版本的 Server 包:

    text
    https://update.code.visualstudio.com/commit:<commit_id>/server-linux-x64/stable

    其中 <commit_id> 从 VS Code 报错信息里获取,例如 645f29cc3176500b4b5762ba887cf2a7f0ffdf2c。

  2. 将下载的 vscode-server-linux-x64.tar.gz 放到 Windows 路径,例如 E:\Downloads\。

  3. 在 WSL 终端中解压到目标目录:

    bash
    mkdir -p ~/.vscode-server/bin/<commit_id>
    cp "/mnt/e/Downloads/vscode-server-linux-x64.tar.gz" /tmp/
    tar -xzf /tmp/vscode-server-linux-x64.tar.gz -C /tmp/
    cp -r /tmp/vscode-server-linux-x64/* ~/.vscode-server/bin/<commit_id>/
    chmod +x ~/.vscode-server/bin/<commit_id>/bin/code-server
  4. 在 PowerShell 中执行 wsl --shutdown,重新进入 WSL,再执行 cd ~/projects && code .。

✅ 验证:VS Code 秒连,左下角显示 WSL: Ubuntu-24.04,不再报 1006。

11.2 Temporary failure in name resolution ​

原因:WSL DNS 解析失败。

解决:按第 2.5 节永久修复 DNS。

bash
sudo apt install -y libjaylink-dev

11.4 OpenOCD 找不到 jimtcl ​

bash
sudo apt install -y libjim-dev

11.5 WSL 里看不到 USB 调试器 ​

使用 usbipd-win 透传,见第 13 节。

11.6 wsl -d Ubuntu-24.04 提示“不存在具有所提供名称的分发” ​

查看实际名称:

powershell
wsl --list --verbose

使用列表中的实际名字启动。

11.7 安装 Ubuntu 后启动失败:无法将磁盘 ... ext4.vhdx 附加到 WSL2: 系统找不到指定的文件 ​

发行版损坏,需重装:

powershell
wsl --unregister Ubuntu
wsl --install -d Ubuntu-24.04

11.8 WSL2 网络问题:ip addr 只有 lo,没有 eth0 ​

现象 ​

启动 WSL 时提示:

text
wsl: 无法配置网络 (networkingMode Nat),回退到 networkingMode VirtioProxy。

在 WSL 中执行:

bash
ip addr
ip route

只显示 lo,没有 eth0 或其他网络接口,ip route 无输出。

bash
ping -c 3 8.8.8.8

报错:

text
ping: connect: Network is unreachable
bash
ping -c 3 mirrors.huaweicloud.com

报错:

text
ping: mirrors.huaweicloud.com: Temporary failure in name resolution

原因 ​

WSL2 通过虚拟网卡连接到 Windows 的网络。NAT 模式配置失败后回退到 VirtioProxy,但虚拟网卡未成功创建,导致 WSL 完全没有网络出口。

不是 DNS 问题,是 WSL 虚拟网络层未初始化。

排查过程(本机实际执行) ​

1. 查看 WSL 网络接口 ​
bash
ip addr
ip route

结果:只有 lo,无 eth0,无默认路由。

2. 查看 .wslconfig 内容 ​

【Windows PowerShell】

powershell
Get-Content $env:USERPROFILE\.wslconfig

本机输出:

text
[wsl2]
networkingMode=mirrored
dnsTunneling=true
autoProxy=false

发现问题:autoProxy=false。

3. 检查 Windows 虚拟化功能 ​

【Windows PowerShell】(管理员)

powershell
Get-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform
Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

本机结果:

  • VirtualMachinePlatform:State : Enabled
  • Microsoft-Windows-Subsystem-Linux:State : Enabled

功能正常。

4. 检查 Windows 网络适配器 ​

【Windows PowerShell】

powershell
Get-NetAdapter -IncludeHidden | Format-Table Name, InterfaceDescription, Status

本机输出中包含:

text
WLAN         无线网卡                Up
以太网         有线网卡                Disconnected

无线网卡正常,其他虚拟网卡不存在(无冲突)。

解决过程(本机实际执行) ​

第一步:将 autoProxy 改回 true ​

【Windows PowerShell】

powershell
notepad $env:USERPROFILE\.wslconfig

改成:

ini
[wsl2]
networkingMode=mirrored
dnsTunneling=true
autoProxy=true

保存,关闭记事本。

第二步:彻底重启 WSL ​

【Windows PowerShell】

powershell
wsl --shutdown

等待 15–30 秒。

确认已停止:

powershell
wsl --list --verbose

本机输出:

text
  NAME            STATE           VERSION
* Ubuntu-24.04    Stopped         2
第三步:重新进入 WSL ​

【Windows PowerShell】

powershell
wsl -d Ubuntu-24.04
第四步:检查虚拟网卡是否恢复 ​
bash
ip addr
ip route

本机恢复正常时的输出:

text
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 ...
    inet 192.168.1.100/24 brd 192.168.1.255 scope global eth0
3: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 ...
    inet 127.0.0.1/8 scope host lo
default via 192.168.1.1 dev eth0 proto kernel

有虚拟网卡、有 IP、有默认路由。

第五步:验证网络 ​
bash
curl -I http://mirrors.huaweicloud.com --connect-timeout 5

本机输出:

text
HTTP/1.1 301 Moved Permanently
Server: elb

TCP 通了。

bash
sudo apt update

本机输出:

text
Hit:1 http://mirrors.huaweicloud.com/ubuntu noble InRelease
All packages are up to date.

apt 正常。

关键发现(本机验证) ​

1. autoProxy=false 会导致 WSL 虚拟网络挂掉 ​

在修复 VS Code 1006 错误时,曾将 .wslconfig 中的 autoProxy 改为 false。之后 WSL 网络无法启动,ip addr 只有 lo。

改回 autoProxy=true 后,虚拟网卡恢复,网络正常。

2. ping 不通但 curl 通 ​

网络恢复后,ping -c 3 8.8.8.8 仍然 100% 丢包:

text
3 packets transmitted, 0 received, 100% packet loss

但 curl 正常返回 HTTP 响应。

结论:ICMP 被网络环境屏蔽,TCP 正常即可。判断网络是否可用,应使用 curl 或 apt update,不能只依赖 ping。

3. /etc/resolv.conf 丢失 ​

执行 sudo rm -f /etc/resolv.conf 后,文件未自动重建:

text
cat: /etc/resolv.conf: No such file or directory

手动写入 DNS:

bash
sudo bash -c 'echo "nameserver 8.8.8.8" > /etc/resolv.conf'
sudo bash -c 'echo "nameserver 223.5.5.5" >> /etc/resolv.conf'

但如果 ip addr 没有虚拟网卡,写 DNS 也无效。先确保有网卡,再管 DNS。

4. chattr +i /etc/resolv.conf 在 WSL2 中不生效 ​
bash
lsattr /etc/resolv.conf

报错:

text
lsattr: Operation not supported While reading flags on /etc/resolv.conf

WSL2 的 /etc 位于虚拟磁盘,不支持 chattr。原笔记第 2.5 节的 chattr +i 写法在 WSL2 中不可用。

最终可用的 .wslconfig ​

ini
[wsl2]
networkingMode=mirrored
dnsTunneling=true
autoProxy=true

本机验证结果 ​

项目结果
WSL 版本2.6.3.0
内核版本6.6.87.2-1
网络模式mirrored
ip addr显示 eth0,有 IP 和默认路由
curl 测试返回 HTTP/1.1 301
apt update成功
虚拟网卡✅ 正常
网络状态✅ 恢复

11.9 RISC-V 工具链:nosys.specs 缺失与 picolibc 编译问题 ​

现象 1:找不到 nosys.specs ​

bash
riscv64-unknown-elf-gcc --specs=nosys.specs -o hello_riscv.elf hello.c

报错:

text
riscv64-unknown-elf-gcc: fatal error: cannot read spec file 'nosys.specs': No such file or directory

原因 ​

Ubuntu 24.04 的 gcc-riscv64-unknown-elf 包不自带 newlib,因此没有 nosys.specs。ARM 工具链自带 newlib,所以有 nosys.specs;RISC-V 使用的是 picolibc。

安装 picolibc ​

bash
sudo apt install -y picolibc-riscv64-unknown-elf

验证安装:

bash
find /usr -name "picolibc.specs" 2>/dev/null | grep riscv

输出:

text
/usr/lib/gcc/riscv64-unknown-elf/13.2.0/picolibc.specs
/usr/lib/picolibc/riscv64-unknown-elf/picolibc.specs

现象 2:使用 picolibc 编译报错 ​

bash
riscv64-unknown-elf-gcc --specs=picolibc.specs -o hello_riscv.elf hello.c

报错:

text
relocation truncated to fit: R_RISCV_HI20 against `.LC0'
undefined reference to `stdout'

原因:

  • R_RISCV_HI20:默认代码模型 medlow 无法处理高地址,需要 medany。
  • stdout 未定义:picolibc 不提供标准输出定义,需用户自行实现。

最终验证方案:最小程序(不依赖 libc) ​

创建最小程序 hello_riscv_min.c:

bash
cat > hello_riscv_min.c << 'EOF'
void _start(void) {
    volatile int x = 42;
    (void)x;
    while (1) {
    }
}
EOF

编译:

bash
riscv64-unknown-elf-gcc -nostdlib -ffreestanding -mcmodel=medany -o hello_riscv.elf hello_riscv_min.c

验证:

bash
file hello_riscv.elf

输出:

text
hello_riscv.elf: ELF 64-bit LSB executable, UCB RISC-V, RVC, double-float ABI, version 1 (SYSV), statically linked, not stripped

进一步确认架构:

bash
riscv64-unknown-elf-readelf -h hello_riscv.elf | head -n 20

输出包含:

text
Class:                             ELF64
Machine:                           RISC-V

结论:RISC-V 交叉编译链路已通。 真实裸机项目需自行编写启动文件和链接脚本,不依赖 picolibc 的 printf。

ARM 与 RISC-V 工具链对比 ​

项目ARMRISC-V
工具链arm-none-eabi-gccriscv64-unknown-elf-gcc
C 库newlibpicolibc
specs 文件nosys.specspicolibc.specs
直接可用性是需额外处理
最小验证方案--specs=nosys.specs-nostdlib -ffreestanding -mcmodel=medany
裸机开发需 startup + linker需 startup + linker

入门阶段建议:

  • ARM:直接用 --specs=nosys.specs,简单可靠。
  • RISC-V:用 -nostdlib -ffreestanding -mcmodel=medany 最小程序验证编译链路即可。

12. ARM 裸机编译验证 ​

在 /home/user/projects 下新建 hello.c:

c
#include <stdio.h>
int main() {
    printf("Hello, ARM!\n");
    return 0;
}

直接编译会报错:

bash
arm-none-eabi-gcc -o hello.elf hello.c
# 报错:undefined reference to `_exit` / `_sbrk` / `_write` ...

原因:裸机环境缺少 newlib 所需的系统调用 stub。

解决:编译时加 --specs=nosys.specs,让工具链链接空 stub。

bash
arm-none-eabi-gcc --specs=nosys.specs -o hello.elf hello.c

即使出现 warning: _close is not implemented... 等警告,也不影响编译。

验证:

bash
file hello.elf

预期:

text
hello.elf: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked, with debug_info, not stripped

注意:此时 printf 在裸机上没有输出终端,只是验证编译链路已通。做真实 STM32/RA 项目时,需要额外提供:

  • startup 文件(启动汇编)
  • 链接脚本 .ld
  • syscalls stub(实现 _write 到串口等)
  • 重定向 printf 输出到串口

13. QEMU 运行 ARM 裸机程序 ​

本节记录在 WSL2 Ubuntu 24.04 中,使用 QEMU 模拟 LM3S6965EVB 开发板,运行 ARM Cortex-M3 裸机程序并输出串口信息的完整过程。

13.1 安装 QEMU ​

bash
sudo apt update
sudo apt install -y qemu-system-arm

✅ 验证:

bash
qemu-system-arm --version

本机输出:

text
QEMU emulator version 8.2.2 (Debian 1:8.2.2+ds-0ubuntu1.18)
Copyright (c) 2003-2023 Fabrice Bellard and the QEMU Project developers

13.2 新建项目目录 ​

bash
mkdir -p ~/projects/learn_embedded/qemu_arm
cd ~/projects/learn_embedded/qemu_arm
pwd

预期:

text
/home/user/projects/learn_embedded/qemu_arm

13.3 编写 main.c(含中断向量表) ​

⚠️ Cortex-M 系列必须提供中断向量表:地址 0 存放初始 SP,地址 4 存放 Reset_Handler(即 _start)。否则程序会跑飞,QEMU 无串口输出。

逐条输入:

bash
cat > main.c << 'EOF'

逐行输入:

c
#include <stdint.h>

#define UART0_DR (*(volatile unsigned int *)0x4000C000)

void _start(void);

__attribute__((section(".vectors")))
const void *vectors[] = {
    (void *)0x20001000,
    (void *)_start,
};

void _start(void) {
    const char *s = "Hello, ARM QEMU!\n";
    while (*s) {
        UART0_DR = *s++;
    }
    while (1) {
    }
}

最后单独一行:

text
EOF

验证:

bash
cat main.c

13.4 编写 linker.ld(含 .vectors 段) ​

逐条输入:

bash
cat > linker.ld << 'EOF'

逐行输入:

ld
ENTRY(_start)

SECTIONS
{
    . = 0x00000000;

    .vectors : {
        *(.vectors)
    }

    .text : {
        *(.text*)
    }

    .rodata : {
        *(.rodata*)
    }

    .data : {
        *(.data*)
    }

    .bss : {
        *(.bss*)
        *(COMMON)
    }
}

最后单独一行:

text
EOF

验证:

bash
cat linker.ld

13.5 编译 ​

bash
arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -nostdlib -T linker.ld -o hello_arm.elf main.c

✅ 验证:

bash
file hello_arm.elf

预期:

text
hello_arm.elf: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked, not stripped

进一步验证入口地址:

bash
arm-none-eabi-objdump -d hello_arm.elf | head -n 20

预期 _start 位于 0x8 或附近:

text
00000008 <_start>:
   8:   b480            push    {r7}
   ...

13.6 使用 QEMU 运行 ​

bash
qemu-system-arm -M lm3s6965evb -kernel hello_arm.elf -nographic -serial mon:stdio

预期输出:

text
Timer with period zero, disabling
Hello, ARM QEMU!

✅ 验证:看到 Hello, ARM QEMU! 即成功。

退出 QEMU:

text
先按 Ctrl + A,松开,再按 X

如果退不出来,直接按 Ctrl + C。

13.7 踩坑记录 ​

13.7.1 无中断向量表 → 无输出 ​

现象:

text
Timer with period zero, disabling

没有 Hello, ARM QEMU!。

原因:Cortex-M 从地址 0 取初始 SP,地址 4 取 PC。没有向量表,PC 跳转到垃圾地址,程序跑飞。

解决:在 main.c 中添加 .vectors 段,并在 linker.ld 中最先放置 .vectors。

13.7.2 versatilepb 机器类型无串口输出 ​

bash
qemu-system-arm -M versatilepb -kernel hello_arm.elf -nographic

现象:

text
pulseaudio: set_sink_input_volume() failed
QEMU: Terminated

无串口输出。

原因:versatilepb 的 UART 未正确重定向到 -nographic 终端。

解决:放弃该机器类型,改用 lm3s6965evb。

13.7.3 microbit 机器类型 Lockup ​

bash
qemu-system-arm -M microbit -kernel hello_arm.elf -nographic

现象:

text
qemu: fatal: Lockup: can't escalate 3 to HardFault (current priority -1)

原因:Cortex-M0 强制要求向量表,缺少时直接 Lockup。

解决:放弃 microbit,改用 lm3s6965evb。

13.8 最终可用的完整命令 ​

bash
cd ~/projects/learn_embedded/qemu_arm

arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -nostdlib -T linker.ld -o hello_arm.elf main.c

qemu-system-arm -M lm3s6965evb -kernel hello_arm.elf -nographic -serial mon:stdio

输出:

text
Timer with period zero, disabling
Hello, ARM QEMU!

13.9 本机验证结果 ​

项目结果
QEMU 版本8.2.2
机器类型lm3s6965evb
CPUCortex-M3
编译工具arm-none-eabi-gcc 13.2.1
ELF 架构ARM, EABI5
串口输出Hello, ARM QEMU!
验证状态✅ 通过

14. WSL2 使用物理调试器:USB 透传 ​

WSL2 默认不能直接访问 Windows 的 USB 设备。 使用 ST-Link / J-Link / CMSIS-DAP 等调试器时,需要用 usbipd-win 把 USB 设备从 Windows 透传给 WSL。

本机实测:usbipd-win 5.3.0,Windows PowerShell,Ubuntu 24.04 WSL2。

14.1 安装 usbipd-win ​

在 Windows PowerShell 中执行:

powershell
winget install --interactive --exact dorssel.usbipd-win

安装过程中:

  • 出现协议提示时输入 Y 回车。
  • 弹出 UAC 时点“是”。
  • 安装向导按提示完成。

✅ 验证:

powershell
usbipd --version

预期输出类似:

text
5.3.0-54+Branch.master.Sha.aa3db8b82c4cb5071fd31bc54211606c70886912...

⚠️ 踩坑记录:winget 无法识别

现象:

text
winget : 无法将“winget”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。

解决:以管理员身份打开 PowerShell,执行:

powershell
$progressPreference = 'silentlyContinue'
Install-PackageProvider -Name NuGet -Force | Out-Null
Install-Module -Name Microsoft.WinGet.Client -Force -Repository PSGallery | Out-Null
Repair-WinGetPackageManager

完成后关闭并重新打开 PowerShell,验证:

powershell
winget --version

预期:v1.29.290 或更高。

14.2 查看 USB 设备 ​

插上调试器后,在 Windows PowerShell 执行:

powershell
usbipd list

输出示例:

text
Connected:
BUSID  VID:PID    DEVICE                                                        STATE
2-4    30fa:0300  USB 输入设备                                                  Not shared
2-9    048d:c101  USB 输入设备                                                  Not shared
2-14   8087:0026  蓝牙设备                                              Not shared

字段解释:

字段含义
BUSID设备编号,后面 bind / attach 要用
VID:PID厂商 ID : 产品 ID
DEVICE设备名称
STATENot shared = 尚未共享给 WSL

本机当前只识别到鼠标、键盘、蓝牙,没有调试器。 插上 ST-Link / J-Link / CMSIS-DAP 后,会多出一行对应设备。

14.3 绑定设备(只需一次) ​

找到调试器的 BUSID,例如 2-5,执行:

powershell
usbipd bind --busid 2-5

⚠️ 不要写 <BUSID>。 PowerShell 里 < > 是特殊符号,会报:

text
“<”运算符是为将来使用而保留的。

正确写法是直接写真实编号,例如 2-5。

✅ 验证:

powershell
usbipd list

对应设备的 STATE 应从 Not shared 变为 Shared。

14.4 附加到 WSL(每次插拔后都要做) ​

powershell
usbipd attach --wsl --busid 2-5

如果需要插上自动附加:

powershell
usbipd attach --wsl --busid 2-5 --auto-attach

✅ 在 WSL Ubuntu 中验证:

bash
sudo apt install -y usbutils
lsusb

预期能看到调试器,例如:

text
Bus 001 Device 005: ID 0483:3748 STMicroelectronics ST-LINK/V2

14.5 用完还给 Windows ​

powershell
usbipd detach --busid 2-5

14.6 常用命令速查 ​

命令作用
usbipd list列出所有 USB 设备
usbipd bind --busid X-Y绑定设备,只需一次
usbipd attach --wsl --busid X-Y把设备给 WSL
usbipd detach --busid X-Y把设备还给 Windows
usbipd unbind --busid X-Y取消绑定
usbipd attach --wsl --busid X-Y --auto-attach插上自动给 WSL

14.7 验证 OpenOCD 能否识别调试器 ​

在 WSL Ubuntu 中:

bash
lsusb
openocd -f interface/stlink.cfg -f target/stm32f1x.cfg

如果 OpenOCD 能连上目标芯片,说明 USB 透传成功。

注意:target/stm32f1x.cfg 只是示例,实际芯片型号要换成对应的配置文件。


15. 附:Windows 原生 MSYS2 UCRT64 方案(备用) ​

本方案已独立成篇,详见: 17 Windows MSYS2 UCRT64 RISC-V 工具链搭建实战 · 备用方案

注意:该方案与 WSL 方案互相独立,不要混用。

16. 使用规范与注意事项 ​

  1. 本机主用方案:WSL2 + Ubuntu 24.04。
  2. 备用方案:Windows + MSYS2 UCRT64。
  3. 不要混用:
    • WSL 中的工具链在 /usr/bin、/usr/local/bin。
    • MSYS2 中的工具链在 E:\msys64\ucrt64\bin。
    • 同时使用会导致 PATH 冲突、OpenOCD 脚本路径不一致、编译结果差异。
  4. 代码存放:
    • WSL 方案:/home/user/projects。
    • MSYS2 方案:E:\projects 等 Windows 路径。
  5. VS Code 连接:
    • WSL 方案:WSL: Connect to WSL → Ubuntu-24.04。
    • MSYS2 方案:直接打开 Windows 文件夹,使用 PowerShell 终端。
  6. 不要以管理员身份运行 VS Code 连接 WSL,容易权限冲突。
  7. 不要在 WSL 里执行 wsl 命令,那是 Windows PowerShell 的命令。
  8. 不要在 WSL 环境下直接打开 Windows 盘的项目文件夹,会导致文件挂载超时,触发 1006 错误。
  9. USB 透传:WSL 里用调试器必须通过 usbipd-win。
    插拔后要重新 usbipd attach --wsl --busid X-Y。
    不要写 <BUSID>,直接写真实编号。

17. 最终状态记录 ​

已完成并验证:

  • Windows 11 家庭版 25H2 安装 WSL2。
  • WSL 版本 2.6.3.0,内核 6.6.87.2-1。
  • WSL 发行版名:Ubuntu-24.04,系统版本:Ubuntu 24.04.5 LTS。
  • WSL 中用户名:自定义。
  • 华为云源已配置,APT 强制 IPv4 已配置。
  • DNS 已永久修复。
  • VS Code 安装 WSL 扩展,可连接 Ubuntu-24.04。
  • VS Code 远程资源管理器显示 WSL 和 SSH。
  • Windows 文件资源管理器可通过 \\wsl.localhost\Ubuntu-24.04 访问 Linux 文件。
  • ARM GCC 13.2.1 已安装验证。
  • RISC-V GCC 13.2.0 已安装验证。
  • gdb-multiarch 15.1 支持 ARM / RISC-V。
  • CMake 3.28.3、Make 4.3、GCC 13.3.0 已安装验证。
  • OpenOCD 0.12.0+dev 已从源码编译安装,路径 /usr/local/bin/openocd,启用 J-Link / ST-Link / CMSIS-DAP / KitProg / USB-Blaster-2 / FTDI / sysfsgpio / bcm2835gpio。
  • 已完成 ARM 裸机编译验证,hello.elf 文件类型为 ELF 32-bit LSB executable, ARM, EABI5。
  • 后续可使用 gdb-multiarch + OpenOCD 调试 ARM / RISC-V 程序。
  • WSL2 使用物理调试器时通过 usbipd-win USB 透传。
  • usbipd-win 5.3.0 已安装,可用于 ST-Link / J-Link / CMSIS-DAP USB 透传。
  • Windows 原生 MSYS2 UCRT64 方案已独立记录,作为备用:17 Windows MSYS2 UCRT64 RISC-V 工具链搭建实战 · 备用方案。
  • WSL2 虚拟网络问题已解决:.wslconfig 使用 networkingMode=mirrored + dnsTunneling=true + autoProxy=true,ip addr 正常显示 eth0 网卡和默认路由,curl 和 apt 均可用。
  • QEMU 8.2.2 已安装,成功在 lm3s6965evb 机器上运行 ARM Cortex-M3 裸机程序,串口输出 Hello, ARM QEMU!。

这份笔记可直接作为 WSL2 Ubuntu 24.04 嵌入式开发环境的完整配置记录。 换电脑或重装环境时,按顺序执行即可。


🔗 相关文章 ​

最近更新