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

如何通过Rust-Cargo实现部分依赖crate的动态链接?

实现方案

可以通过修改各个 crate 的 Cargo.toml 配置来实现需求,无需手动执行 rustc 命令:

1. 配置 engine 编译为动态库(dylib)

在 engine/Cargo.toml 中添加 [lib] 段,明确指定 crate 类型为动态库:

[package]
name = "engine"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["dylib"]  # 强制编译为动态链接库

2. 配置 test_static 编译为静态库(rlib)

rlib 是 Rust 库的默认编译类型,可显式配置确保行为明确,在 test_static/Cargo.toml 中添加:

[package]
name = "test_static"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["rlib"]  # 明确编译为静态链接库(默认值,可省略)

3. 配置 sandbox 实现混合链接

修改 sandbox/Cargo.toml,移除不必要的 prefer-dynamic 依赖,同时通过 profile 配置确保全局静态链接(包括标准库),而 engine 作为 dylib 会被自动动态链接:

[package]
name = "sandbox"
version = "0.1.0"
edition = "2021"
# build = "build.rs" 若无需构建脚本可移除

[dependencies]
engine = { path = "../engine" }
test_static = { path = "../test_static" }

[profile.dev]
rustflags = ["-C", "prefer-static"]  # 默认静态链接所有依赖(含标准库)

[profile.release]
rustflags = ["-C", "prefer-static"]  # 发布版本同样配置

原理说明

  • Rust 的 dylib 类型 crate 只能被动态链接,因此当 engine 被配置为 dylib 后,sandbox 会自动选择动态链接它。
  • rlib 类型 crate 默认会被静态链接,配合 prefer-static 标志,可确保标准库和 test_static 都以静态方式链接到 sandbox 二进制文件中。
  • 这种配置既满足了混合链接的需求,又避免了全局 prefer-dynamic 导致标准库被动态链接的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:50:13