假设我有三个板条箱:foo、bar和baz。
Cargo.toml
[workspace]
members = [
"foo",
"bar",
"baz",
]
[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"foo/Cargo.toml
[package]
name = "foo"
version = "0.1.0"
edition = "2018"
[lib]
name = "foo"
crate-type = ["staticlib"]
[dependencies]
bar = { path = "../bar", default-features = false }foo/src/lib.rs
#![no_std]
extern crate bar as _;
use core::alloc::{GlobalAlloc, Layout};
#[global_allocator]
static ALLOCATOR: Allocator = Allocator;
struct Allocator;
unsafe impl GlobalAlloc for Allocator {
unsafe fn alloc(&self, _: Layout) -> *mut u8 {
todo!()
}
unsafe fn dealloc(&self, _: *mut u8, _: Layout) {
todo!()
}
}bar/Cargo.toml
[package]
name = "bar"
version = "0.1.0"
edition = "2018"
[lib]
name = "bar"
[features]
default = ["heap"]
heap = []bar/src/lib.rs
#![no_std]
#![feature(alloc_error_handler)]
use core::alloc::GlobalAlloc;
use core::alloc::Layout;
extern crate alloc;
#[cfg(feature = "heap")]
#[global_allocator]
static ALLOCATOR: Allocator = Allocator;
struct Allocator;
unsafe impl GlobalAlloc for Allocator {
unsafe fn alloc(&self, _: Layout) -> *mut u8 {
todo!()
}
unsafe fn dealloc(&self, _: *mut u8, _: Layout) {
todo!()
}
}
#[panic_handler]
fn panic(_: &core::panic::PanicInfo<'_>) -> ! {
todo!();
}
#[alloc_error_handler]
fn alloc_fail(_: Layout) -> ! {
todo!();
}baz/Cargo.toml
[package]
name = "baz"
version = "0.1.0"
edition = "2018"
[lib]
name = "baz"
crate-type = ["staticlib"]
[dependencies]
bar = { path = "../bar" }baz/src/lib.rs
#![no_std]
extern crate bar as _;在这里,bar提供全局分配程序,foo和baz都依赖于bar。然而,foo不允许bar的全局分配器使用它的原始分配器,因此foo依赖于bar,而没有默认的特性。
在每个目录(foo/、bar/和baz/)上运行foo/成功。但是,在项目根目录上运行命令会导致错误:
%cargo clippy
Checking bar v0.1.0 (/tmp/tmp.wlBjM4wNFx/bar)
Checking baz v0.1.0 (/tmp/tmp.wlBjM4wNFx/baz)
Checking foo v0.1.0 (/tmp/tmp.wlBjM4wNFx/foo)
error: the `#[global_allocator]` in this crate conflicts with global allocator in: bar
error: could not compile `foo` due to previous error实际上,由于foo使用其原始全局分配程序并禁用bar的全局分配程序,因此不存在全局分配程序冲突。如何避免此错误?
版本
rustup 1.24.3 (ce5817a94 2021-05-31)
cargo 1.56.0-nightly (b51439fd8 2021-08-09)
rustc 1.56.0-nightly (0035d9dce 2021-08-16)发布于 2021-08-30 00:30:36
这是工作区的属性。bjorn3说论祖利普
如果foo、bar和baz都被编译在一起,那么如果foo或baz依赖于堆特性,就会为bar全局启用堆特性。Cargo将结合每个依赖的机箱所需的所有特性,并使用这些特性编译依赖关系一次。
因此,bar是用heap特性编译的,因为baz需要它,在编译foo时也启用了它的特性。因此,foo和bar的全局分配器同时启用,导致错误。
https://stackoverflow.com/questions/68955652
复制相似问题