You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行anchor build构建时提示target is not supported编译报错

问题描述

执行anchor build命令构建Solana项目时触发编译失败,核心报错来自getrandom依赖包。
完整报错信息如下:

error: target is not supported
   --> /Users/mac/.cargo/registry/src/github.com-1ecc6299db9ec823/getrandom-0.1.16/src/lib.rs:267:9
    |
267 | /         compile_error!("\
268 | |             target is not supported, for more information see: \
269 | |             官方说明文档\
270 | |         ");
    | |___________^

error[E0433]: failed to resolve: use of undeclared crate or module `imp`
   --> /Users/mac/.cargo/registry/src/github.com-1ecc6299db9ec823/getrandom-0.1.16/src/lib.rs:292:5
    |
292 |     imp::getrandom_inner(dest)
    |     ^^^ use of undeclared crate or module `imp`

For more information about this error, try `rustc --explain E0433`.
error: could not compile `getrandom` due to 2 previous errors
warning: build failed, waiting for other jobs to finish...
error: build failed
环境信息
  • solana-cli 1.8.13 (src:42c3fbc1; feat:1006352700)
  • rustup 1.24.3 (ce5817a94 2021-05-31)
  • rustc 1.61.0 (fe5b13d68 2022-05-18)
  • anchor-cli 0.24.2
故障原因

当前使用的rustc 1.61.0版本和Anchor 0.24.2、Solana 1.8.13的依赖链不兼容:旧版本getrandom 0.1.16没有适配高版本Rust下的Solana BPF编译目标,无法生成对应平台的底层实现模块imp,最终触发编译错误。

解决步骤

优先选择版本对齐方案,稳定性最高:

  1. 安装与当前Solana、Anchor版本适配的Rust 1.59.0版本,设置为全局默认:
    rustup install 1.59.0
    rustup default 1.59.0
    
  2. 为Solana编译目标添加对应工具链支持:
    rustup target add bpfel-unknown-unknown --toolchain 1.59.0
    
  3. 清理旧构建缓存后重新执行构建:
    cargo clean
    anchor build
    

如果需要保留全局高版本Rust,可使用依赖补丁方案:

  1. 在项目根目录的Cargo.toml末尾添加如下配置,强制替换getrandom依赖版本:
    [patch.crates-io]
    getrandom = { version = "0.2", features = ["custom"] }
    
  2. 在程序入口文件(路径一般为programs/<你的项目名>/src/lib.rs)的顶部添加自定义随机数实现,适配Solana运行环境:
    #[cfg(target_os = "solana")]
    mod solana_getrandom {
        use getrandom::Error;
        pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
            solana_program::program::random_bytes(dest);
            Ok(())
        }
    }
    getrandom::register_custom_getrandom!(solana_getrandom::getrandom_inner);
    
  3. 清理缓存后重新执行anchor build即可。

内容的提问来源于stack exchange,提问作者苍苍张

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 21:12:35