rust - 如何在 Cargo.toml 中创建目标特定配置文件?

标签 rust rust-cargo toml

我想指定一个单独的[profile.release]对于我的图书馆,当 cfg(target_os = "ios")活跃。我试过这个:

[profile.'cfg(not(target_os = "ios"))'.release]
lto = true # Use link-time optimization.

[profile.'cfg(target_os = "ios")'.release]
lto = true # Use link-time optimization.
opt-level = "z"  # Mobile devices are fast enough. Optimize for size instead.
strip = "symbols" # Not relevant for windows.

但是,当我现在尝试构建我的项目/工作区时,我收到以下错误:

error: failed to parse manifest at `/path/to/Cargo.toml`

Caused by:
  invalid character `(` in profile name `cfg(not(target_os = "ios"))`
  Allowed characters are letters, numbers, underscore, and hyphen.

这是可以预料的,因为根据documentation[profile.<name>]是允许的。

有什么方法可以实现所需的行为吗?

附注完整的目标名称为 aarch64-apple-ios如果需要的话。

最佳答案

这是在 issue #4897, Per-target profiles? 中请求的,但尚未实现。

同时,您可以使用脚本检查目标并设置 environment variables覆盖配置(例如,设置CARGO_PROFILE_RELEASE_LTOCARGO_PROFILE_RELEASE_OPT_LEVEL),然后用它们调用Cargo。

这是一个示例,来自 users.rust-lang.org - How to modify profile.release only for a target?

在工作区中创建一个二进制文件,例如自定义构建。在 custom_build/src/main.rs 中放置:

use std::env;
use std::process::Command;

fn main() {
    let mut cargo = Command::new(env::var_os("CARGO").unwrap());
    cargo.env("CARGO_CUSTOM_BUILD", "1"); // So we can disallow regular builds, to prevent mistakes
    cargo.args(env::args_os().skip(1));

    // You can determine the target OS by various way, but providing it manually to the build script is the simplest.
    let for_ios = env::var("build_ios").is_ok();
    if for_ios {
        cargo.env("CARGO_PROFILE_RELEASE_LTO", "true");
        cargo.env("CARGO_PROFILE_RELEASE_OPT_LEVEL", "z");
        cargo.env("CARGO_PROFILE_RELEASE_STRIP", "symbols");
    } else {
        cargo.env("CARGO_PROFILE_RELEASE_LTO", "true");
    }

    let cargo_succeeded = cargo.status().ok().map_or(false, |status| status.success());
    if !cargo_succeeded {
        std::process::exit(1);
    }
}

然后您可以创建一个 build.rs 文件以防止手动运行 cargo:

use std::env;

fn main() {
    if !env::var("CARGO_CUSTOM_BUILD").ok().map_or(false, |s| s == "1") {
        panic!("Do not run `cargo ...`, run `cargo custom_build ...` instead")
    }
}

关于rust - 如何在 Cargo.toml 中创建目标特定配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72085560/

相关文章:

haskell - Rust 中具有超特征的有界特征参数

rust - 在 Rust 中使用 from_iter 创建 BTreeSet

rust - 用于切换相关 crate 功能的功能

r - 我如何在我的 blogdown 站点的主页上发布一些介绍性段落?

go - 为 TOML 文件和 golang 解析表中的键值对

rust - `RwLockWriteGuard<' _, T>` 没有实现 T 实现的特征

multithreading - 为什么我的 Futures 没有最大化 CPU?

parallel-processing - 如何对并行代码进行基准测试?

c++ - Rust Cargo CMake 与 C++ 库依赖项集成

go - 雨果帖子不显示