RISC-V 想玩起来,第一步,可以先准备软件环境。
官方仓库的 GNU 工具链 riscv-gnu-toolchain 里,有 Spike pk 或 QEMU 的仿真环境,可以一次性把编译和仿真环境都准备好。
准备工具链
前提
如果是 Windows / WSL2 环境,在获取代码前,请确认工作目录属性是区分大小写的。因为 glibc 只能在区分大小写的文件系统上编译。不然,编译时会遇到链接错误,如 undefined reference to 'rtld_errno'。
1# 以管理员权限打开 Windows 终端 2# https://github.com/microsoft/terminal 3 4# 查询工作目录区分大小写属性 5fsutil.exe file queryCaseSensitiveInfo D:\wslcodes 6已禁用目录 D:\wslcodes 的区分大小写属性。 7 8# 启用工作目录区分大小写属性 9fsutil.exe file setCaseSensitiveInfo D:\wslcodes enable 10已启用目录 D:\wslcodes 的区分大小写属性。
如果是 Linux / Ubuntu 环境,那已经是区分大小写的了。
获取代码
1git clone --depth 1 -b master https://github.com/riscv-collab/riscv-gnu-toolchain.git 2cd riscv-gnu-toolchain 3git submodule update --init --recursive
如果不用 QEMU 仿真,可以删除该子模块,加快下载:
1git rm --cached qemu 2git submodule update --init --recursive
编译安装
Ubuntu 20 上的编译过程。其他操作系统,请见工具链的 README。
1# 依赖 2sudo apt update -y 3sudo 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 4# for spike 5sudo apt install device-tree-compiler -y 6 7# 配置 8# --enable-multilib 支持 32-bit 与 64-bit,默认 64-bit 9# --with-sim=spike 带上 Spike 模拟器 (only support rv64* bare-metal/elf toolchain) 10./configure --prefix=/opt/riscv --enable-multilib --with-sim=spike 11 12# 编译 13sudo make linux build-sim 14 15# 环境 16# 可以进 ~/.bashrc,但影响系统 gcc 环境 17export RISCV_HOME=/opt/riscv 18export PATH=$RISCV_HOME/bin:$RISCV_HOME/riscv64-unknown-elf/bin:$PATH 19 20# 测试 21riscv64-unknown-elf-gcc --version 22spike -h
编译程序并运行
编写文件 hello.c:
1#include <stdio.h> 2 3int main(int argc, char const *argv[]) { 4 printf("hello riscv\n"); 5 return 0; 6}
编译程序:
1riscv64-unknown-elf-gcc hello.c -o hello
Spike 运行:
1# 默认 64-bit,故用 pk64,另有 pk32 2$ spike $(which pk64) hello 3bbl loader 4hello riscv 5 6# spike debug 运行 7$ spike -d $(which pk64) hello 8: h
更多资料
GoCoding 个人实践的经验分享,可关注公众号!
