RISC-V 想玩起来,第一步,能够先预备软件环境。

官方仓库的 GNU 东西链 riscv-gnu-toolchain 里,有 Spike pk 或 QEMU 的仿真环境,能够一次性把编译和仿真环境都预备好。

预备东西链

条件

假如是 Windows / WSL2 环境,在获取代码前,请确认工作目录特点是区别大小写的。因为 glibc 只能在区别大小写的文件体系上编译。不然,编译时会遇到链接错误,如 undefined reference to 'rtld_errno'

# 以管理员权限打开 Windows 终端
#  https://github.com/microsoft/terminal
# 查询工作目录区别大小写特点
fsutil.exe file queryCaseSensitiveInfo D:\wslcodes
已禁用目录 D:\wslcodes 的区别大小写特点。
# 启用工作目录区别大小写特点
fsutil.exe file setCaseSensitiveInfo D:\wslcodes enable
已启用目录 D:\wslcodes 的区别大小写特点。

假如是 Linux / Ubuntu 环境,那已经是区别大小写的了。

获取代码

git clone --depth 1 -b master https://github.com/riscv-collab/riscv-gnu-toolchain.git
cd riscv-gnu-toolchain
git submodule update --init --recursive

假如不用 QEMU 仿真,能够删去该子模块,加快下载:

git rm --cached qemu
git submodule update --init --recursive

编译装置

Ubuntu 20 上的编译过程。其他操作体系,请见东西链的 README。

# 依靠
sudo apt update -y
sudo apt install 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 -y
#  for spike
sudo apt install device-tree-compiler -y
# 配置
#  --enable-multilib 支撑 32-bit 与 64-bit,默认 64-bit
#  --with-sim=spike 带上 Spike 模拟器 (only support rv64* bare-metal/elf toolchain)
./configure --prefix=/opt/riscv --enable-multilib --with-sim=spike
# 编译
sudo make linux build-sim
# 环境
#  能够进 ~/.bashrc,但影响体系 gcc 环境
export RISCV_HOME=/opt/riscv
export PATH=$RISCV_HOME/bin:$RISCV_HOME/riscv64-unknown-elf/bin:$PATH
# 测试
riscv64-unknown-elf-gcc --version
spike -h

编译程序并运转

编写文件 hello.c:

#include <stdio.h>
int main(int argc, char const *argv[]) {
  printf("hello riscv\n");
  return 0;
}

编译程序:

riscv64-unknown-elf-gcc hello.c -o hello

Spike 运转:

# 默认 64-bit,故用 pk64,另有 pk32
$ spike $(which pk64) hello
bbl loader
hello riscv
# spike debug 运转
$ spike -d $(which pk64) hello
: h

更多资料

  • RISC-V Wiki
  • GCC RISC-V Options

GoCoding 个人实践的经验共享,可重视大众号!