Search code examples
rustrust-cargo

How can I use cargo build scripts to create a binary


I would like to create a binary from a rust within a rust build script.

I tried to create a file OUT_DIR/bin/hello_from_build_script_binary like this:

use std::env;
use std::fs;
use std::path::Path;

fn main() {
    let out_dir = env::var_os("OUT_DIR").unwrap();
    fs::create_dir_all(format!("{}/bin", out_dir)).unwrap();
    let dest_path = Path::new(&out_dir)
        .join("bin")
        .join("hello_from_build_script_binary.rs");
    fs::write(
        &dest_path,
        "pub fn main() -> &'static str {
            \"Hello from my build script binary!\"
        }
        ",
    )
    .unwrap();
}

And running it like:

$ cargo run --bin hello_from_build_script_binary

which gave me the error

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

Caused by:
  can't find `bar` bin at `src/bin/bello_from_build_script_binary.rs` or `src/bin/bello_from_build_script_binary/main.rs`. Please specify bin.path if you want to use a non-default path.

I also tried putting the binary in OUT_DIR/..


Solution

  • AFAIK the top-level file can't be generated by build.rs and must exist in your src or src/bin folder. But you can have a file named hello_from_build_script_binary.rs in src/bin with just this content:

    include!(concat!(env!("OUT_DIR"), "/bin/hello_from_build_script_binary.rs"));
    

    so that it will include the contents of the generated file, and have the real code generated by build.rs like you're already doing.