RISC-V 工具链搭建
FreeGuideOnline
最新
2026-07-12
bash sudo apt update sudo apt install -y build-essential git wget tar
## 方法一:使用预编译工具链(推荐入门)
RISC-V 官方和 SiFive 提供了预编译的二进制工具链,无需漫长编译,几分钟即可上手。
### 1. 下载工具链
裸机工具链(`elf` 目标)适用于嵌入式开发,不带操作系统支持:
```bash
wget https://github.com/riscv-collab/riscv-gnu-toolchain/releases/download/2024.04.12/riscv64-elf-ubuntu-22.04-gcc-nightly-2024.04.12-nightly.tar.gz
如果你需要开发 RISC-V Linux 应用程序,则下载 Linux 工具链:
wget https://github.com/riscv-collab/riscv-gnu-toolchain/releases/download/2024.04.12/riscv64-glibc-ubuntu-22.04-gcc-nightly-2024.04.12-nightly.tar.gz
若网络较慢,可用镜像或选择更早的稳定版本,文件名相应调整。
2. 解压并安装
将工具链解压到 /opt/riscv(或任意你喜欢的目录):
sudo mkdir -p /opt/riscv
sudo tar -xzf riscv64-elf-ubuntu-22.04-gcc-nightly-2024.04.12-nightly.tar.gz -C /opt/riscv
3. 配置环境变量
将工具链的 bin 目录加入 PATH:
echo 'export PATH=/opt/riscv/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
4. 验证安装
riscv64-unknown-elf-gcc --version
看到版本信息则安装成功。
如果用的是 Linux 工具链,命令为
riscv64-unknown-linux-gnu-gcc --version。
方法二:从源码构建工具链(可定制)
如果你需要特定配置(如开启压缩指令、多库支持),或希望使用最新代码,可以从源码编译。
1. 安装编译依赖
sudo apt install -y autoconf automake autotools-dev curl python3 libmpc-dev \
libmpfr-dev libgmp-dev gawk build-essential bison flex texinfo gperf \
libtool patchutils bc zlib1g-dev libexpat-dev ninja-build
2. 克隆仓库
git clone --recursive https://github.com/riscv/riscv-gnu-toolchain
cd riscv-gnu-toolchain
3. 配置与编译
裸机工具链(支持 rv64imac 扩展,newlib 库):
./configure --prefix=/opt/riscv --with-arch=rv64imac --with-abi=lp64
make -j$(nproc)
Linux 工具链(glibc,rv64gc):
./configure --prefix=/opt/riscv
make linux -j$(nproc)
编译过程可能持续 30~60 分钟。
4. 安装
sudo make install
之后同样将 /opt/riscv/bin 加入 PATH 即可。
搭建 RISC-V 模拟环境
有了工具链,还需要模拟器来运行程序。
安装 Spike 模拟器
Spike 是 RISC-V 官方的指令级模拟器,适合裸机程序的验证。
git clone https://github.com/riscv-software-src/riscv-isa-sim.git
cd riscv-isa-sim
mkdir build && cd build
../configure --prefix=/opt/riscv
make -j$(nproc)
sudo make install
默认 Spike 会安装到 /opt/riscv/bin/spike,且需要设备树和 BBL 支持。简单测试可使用 Proxy Kernel(pk):
git clone https://github.com/riscv-software-src/riscv-pk.git
cd riscv-pk
mkdir build && cd build
../configure --prefix=/opt/riscv --host=riscv64-unknown-elf
make -j$(nproc)
sudo make install
使用 QEMU 用户模式(更简单)
如果你主要开发 Linux 应用,qemu-user 可以直接运行 RISC-V 二进制,无需完整系统镜像。
sudo apt install qemu-user
运行 RISC-V 程序:
qemu-riscv64 ./hello
测试你的第一个 RISC-V 程序
裸机“Hello World”(用 Spike + pk)
编写 C 文件 hello.c:
#include <stdio.h>
int main() {
printf("Hello RISC-V!\n");
return 0;
}
编译:
riscv64-unknown-elf-gcc -o hello hello.c
使用 Spike 配合 pk 运行:
spike pk hello
输出 Hello RISC-V! 即成功。
Linux 应用测试
用 Linux 工具链编译:
riscv64-unknown-linux-gnu-gcc -static -o hello_static hello.c # 静态链接避免依赖
qemu-riscv64 ./hello_static