嵌入式应用开alloc特性仍报错:找不到alloc crate(thumbv8m.main-none-eabi)
问题
在目标为thumbv8m.main-none-eabi的嵌入式应用中引入依赖ff crate的some-crate库,已在Cargo.toml开启alloc特性且确认目标已安装,但编译时仍报错error[E0463]: 无法找到alloc crate。
项目结构
embd-app <-- 嵌入式应用,引入some-crate |--.cargo/config |--Cargo.toml |--src |--main.rs some-crate <-- 依赖ff crate的库 |--Cargo.toml |--src |--lib.rs
配置代码
embd-app/.cargo/config
[build] target = "thumbv8m.main-none-eabi" [unstable] build-std = ["core"]
embd-app/Cargo.toml
[dependencies] some-crate = { path = "../some-crate", default-features = false , features = ["alloc"] }
embd-app/src/main.rs
#![no_std] #![no_main] /// some code
some-crate/Cargo.toml
[package] name = "some-crate" version = "0.1.0" edition = "2021" [dependencies] ff = { version="0.13.0", default-features = false } [features] default = ["std"] alloc = ["ff/alloc"] std = ["alloc"]
some-crate/src/lib.rs
// The code is minimized just to generate an error #![no_std] #[cfg(feature = "alloc")] extern crate alloc; use alloc::{vec, vec::Vec}; pub fn foo() -> Vec<u8> { vec![1, 2] }
已安装目标
$ rustup target list | grep installed aarch64-apple-darwin (installed) thumbv8m.main-none-eabi (installed)
编译报错
error[E0463]: can't find crate for `alloc` --> /Users/foobar/.cargo/registry/src/github.com-1ecc6299db9ec823/ff-0.13.0/src/lib.rs:10:1 | 10 | extern crate alloc; | ^^^^^^^^^^^^^^^^^^^ can't find crate For more information about this error, try `rustc --explain E0463`. error: could not compile `ff` due to previous error
解决方案
问题核心在于两个点:alloc库未被纳入编译范围,且无操作系统目标缺少全局内存分配器。
1. 修改build-std配置,添加alloc库
编辑embd-app/.cargo/config,将build-std的值改为包含alloc:
[build] target = "thumbv8m.main-none-eabi" [unstable] build-std = ["core", "alloc"]
原因:no_std环境默认仅编译core库,开启alloc特性后必须显式告诉Cargo编译alloc标准库。
2. 提供全局内存分配器
无操作系统的嵌入式目标没有默认内存分配器,必须手动实现或引入第三方分配器:
- 首先在
embd-app/Cargo.toml添加依赖:
[dependencies] some-crate = { path = "../some-crate", default-features = false , features = ["alloc"] } alloc_cortex_m = "0.5" cortex-m = "0.7" cortex-m-rt = "0.7"
- 然后修改
embd-app/src/main.rs,添加分配器初始化和必要的panic处理:
#![no_std] #![no_main] use cortex_m_rt::entry; use alloc_cortex_m::CortexMHeap; // 定义全局分配器 #[global_allocator] static ALLOCATOR: CortexMHeap = CortexMHeap::empty(); #[entry] fn main() -> ! { // 初始化堆内存,大小根据硬件实际情况调整 let heap_size = 1024; unsafe { ALLOCATOR.init( cortex_m::peripheral::SCB::vtor().as_ptr() as usize + 0x800, heap_size ) } // 调用some-crate的功能 let _vec = some_crate::foo(); loop {} } // 实现panic处理器(no_std环境必需) #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} }
内容的提问来源于stack exchange,提问作者user76333
相关产品推荐
相关产品推荐

