基于 RISCV 的裸机程序
基于 RISCV 的裸机程序
配置环境
ansen@ansen-virtual-machine:~$ rustc --version
rustc 1.83.0-nightly (9ff5fc4ff 2024-10-03)
ansen@ansen-virtual-machine:~$ qemu-system-riscv64 --version
QEMU emulator version 7.0.0
Copyright (c) 2003-2022 Fabrice Bellard and the QEMU Project developers
另外安装:
rustup target add riscv64gc-unknown-none-elf
cargo install cargo-binutils
rustup component add rust-src
rustup component add llvm-tools-preview
标准 rust 代码
通过 cargo
生成一段标准代码
cargo new hello
src/main.rs
代码
fn main() {
println!("Hello, world!");
}
运行 cargo run
可以看到执行结果:
ansen@ansen-virtual-machine:~/work/src/tmp/hello$ cargo run
Compiling hello v0.1.0 (/home/ansen/work/src/tmp/hello)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.86s
Running `target/debug/hello`
Hello, world!
如果在 riscv
上运行,需要编译成 riscv
的指令。通过:
cargo run --target riscv64gc-unknown-none-elf
可以生成可执行代码,但会报错
ansen@ansen-virtual-machine:~/work/src/tmp/hello$ cargo run --target riscv64gc-unknown-none-elf
Compiling hello v0.1.0 (/home/ansen/work/src/tmp/hello)
error[E0463]: can't find crate for `std`
|
= note: the `riscv64gc-unknown-none-elf` target may not support the standard library
= note: `std` is required by `hello` because it does not declare `#![no_std]`
= help: consider building the standard library from source with `cargo build -Zbuild-std`
error: cannot find macro `println` in this scope
--> src/main.rs:2:5
|
2 | println!("Hello, world!");
| ^^^^^^^
error: `#[panic_handler]` function required, but not found
error: requires `sized` lang_item
For more information about this error, try `rustc --explain E0463`.
error: could not compile `hello` (bin "hello") due to 4 previous errors
报错的原因是目标平台上没有 rust<