【问题标题】:conditionally set crate-type based on feature根据功能有条件地设置板条箱类型
【发布时间】:2023-01-20 02:12:57
【问题描述】:

我想根据启用的功能有条件地更改我的 Cargo.toml 中的 crate-type 字段。我找不到任何方法来做到这一点。是否可以直接在Cargo.toml 中或通过build.rs 中的某些内容来执行此操作?还是环境变量?

我正在寻找的示例: 如果启用了 b,则只编译 rlib。

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

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[features]
a = []
b = []

['cfg(feature = "a")'.lib]
crate-type = ["staticlib"]

['cfg(feature = "b")'.lib]
crate-type = ["rlib"]

如果您想知道为什么我什至需要这个:

我正在编写一个库,它将被 Rust 应用程序和 C/C++ 应用程序中的 FFI 使用,并且 api 以及一些类型根据启用的功能进行了调整,以便于使用等。

如果我启用所有板条箱类型 ["rlib", "staticlib"],则生成的 .a大量的(12MB+)。

如果我只构建staticlib,它只有 700KB。

如果我只构建rlib,它只有 1.5MB。

是否还有其他潜在原因?也许是货运错误?

【问题讨论】:

  • 您可以尝试使用 [[example]] 作为 crate-type 之一。
  • 以前从未尝试过这样做,但您可以在 Rust 参考中查看 Linkage 以获取选项。您也可以通过代码内属性 #![crate_type = ...] 指定它,这可能有效,或者在 build.rs 脚本中配置它。
  • @kmdreko 好的,是的,这有效
  • @SolomonUcko 有趣的想法,遗憾的是行不通(我在黑白中运行了 cargo clean 以确保)
  • @t348575 太棒了!如果你愿意,你可以自己回答并发布你所做的。

标签: rust rust-cargo


【解决方案1】:

根据@kmdreko

使用 --crate-type= 构建 here

例如:

cargo rustc --features b --crate-type=rlib

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-26
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2022-10-16
    相关资源
    最近更新 更多