在为wasm32-unknown-unknown构建Rust项目时出现错误[E0463]: 找不到名为`core`的crate。

9

我收到以下错误信息:

error[E0463]: can't find crate for `core`
  |
  = note: the `wasm32-unknown-unknown` target may not be installed

error: aborting due to previous error

For more information about this error, try `rustc --explain E0463`.
error: could not compile `cfg-if`

To learn more, run the command again with --verbose.

当我运行以下命令时:
cargo build --target wasm32-unknown-unknown

5
你确定已安装了 wasm32-unknown-unknown 目标?如果没有,请使用 rustup target add wasm32-unknown-unknown 命令进行安装。 - Ivan C
2
rustup target add wasm32-unknown-unknown - Jmb
1个回答

9

关于像corestd这样的crate,有一个特殊之处,因为它们无处不在,所以通常会使用预编译版本,而不是像其他crate那样每次从源代码构建。但是,只有在交叉编译(即使用--target标志)时才会变得明显。

解决这个问题实际上有两个选项,它们也明确说明在 rustc --explain E0463 中 (在线版):

  • [如果]您正在为没有预装std [或core]的目标进行交叉编译,请考虑以下其中一种:
    • 使用rustup target add添加预编译版本的std [或core]
    • 使用cargo build -Z build-std从源代码构建std [或core]

第一个选项(@Ivan和@Jmb已经指出了)很可能是显而易见的:

rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown

第二种选择只适用于每夜版编译器,并需要 rust-src 组件。但如果您不想安装每个目标,或者在编译自定义目标时(即使用一些 JSON 文件的 --target)可能会很有用:
rustup +nightly component add rust-src
cargo +nightly build --target wasm32-unknown-unknown -Z build-std=core

作为一则副笔,与当前稳定版本(1.52)相比,当前夜间版的 Rust 版本中的错误信息已经得到了改进。夜间版编译器将打印:
error[E0463]: can't find crate for `core`
  |
  = note: the `wasm32-unknown-unknown` target may not be installed
  = help: consider downloading the target with `rustup target add wasm32-unknown-unknown`
  = help: consider building the standard library from source with `cargo build -Zbuild-std`

"error[E0433]: failed to resolve: use of undeclared type Box"和其他数百个错误。 - chovy
@chovy 类似Box的类型属于alloc包而不是core,如果您需要使用Box,则必须安装目标std包(例如通过rustup),或者您需要同时编译alloc(例如通过build-std)并自己提供分配器。 - Cryptjar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接