This tutorial shows how to compile and run RISC-V assembler code on Debian Linux systems, which are not running on a RISC-V system (e.g. x86_64).
sudo apt-get install qemu qemu-system-misc qemu-user gcc-riscv64-unknown-elf
Save this as hello.s:
.section .data
msg: .asciz "Hello, World!\n"
.section .text
.globl _start
_start:
# set up the arguments for write syscall
li a7, 64 # system call number for write
li a0, 1 # file descriptor 1 is stdout
la a1, msg # pointer to message
li a2, 14 # length of message string
# make the system call
ecall
# set up the arguments for exit syscall
li a7, 93 # system call number for exit
li a0, 0 # exit status code
# make the system call
ecall
riscv64-unknown-elf-gcc -nostdlib -o hello hello.s
Alternatively you can do it in 2 steps, first creating an obj file, then linking it to the elf file:
riscv64-unknown-elf-as -o hello.o hello.s
riscv64-unknown-elf-ld -o hello hello.o
./hello
You might wonder why you can run the RISC-V program on a x86 system. The reason is that the qemu program registered itself for this type of programs with the binfmt_misc feature of Linux. If there are problems with it, you can also start qemu manually to run the program:
qemu-riscv64 hello
Also note that qemu calls the syscalls of the host operating system. Here is a list of all Linux syscalls: