最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rust - Dynamically configuring constants in embedded compiled child crates - Stack Overflow

programmeradmin1浏览0评论

I'm embedding a compiled binary from a child crate into a parent library. I need to make the constant FOO within the child crate configurable from the parent crate during the build process. How can I achieve this?

Here's my project structure:

- child/
    - src/
        - main.rs
    - Cargo.toml
- src/
    - lib.rs
- Cargo.toml
- build.rs

Here's the code for child/src/main.rs:

const FOO: usize = 42; // How can I configure this value from the parent crate?

fn main() {
    println!("{FOO}");
}

My build.rs script looks like this:

fn main() {
    const CHILD_CRATE_NAME: &str = "child";
    const CHILD_CRATE_DIRNAME: &str = "child";

    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());

    let build = Command::new("cargo")
        .args([
            "build",
            "--package",
            CHILD_CRATE_NAME,
            "--release",
            "--target-dir",
            out_dir.join(CHILD_CRATE_DIRNAME).to_str().unwrap(),
        ])
        .spawn()
        .unwrap();

    build.wait().unwrap();
}

src/lib.rs:

const CHILD: &[u8] = include_bytes!(concat!(
    env!("OUT_DIR"),
    "/child/release/child",
));
// do something with `CHILD` ...
发布评论

评论列表(0)

  1. 暂无评论