• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Create a `build.rs` File
2
3We create a `build.rs` file in our crate's root. Cargo will pick up on the existence of this file, then compile and execute it before the rest of the crate is built.
4This can be used to generate code at compile time.
5And of course in our case, we will be generating Rust FFI
6bindings to `bzip2` at compile time. The resulting bindings will be written to
7`$OUT_DIR/bindings.rs` where `$OUT_DIR` is chosen by `cargo` and is something
8like `./target/debug/build/bindgen-tutorial-bzip2-sys-afc7747d7eafd720/out/`.
9
10Note that the associated shared object to `bz2` is `libbz2.so`. In general, a `lib<name>.so` should be referenced in the build file by `<name>`.
11
12```rust,ignore
13use std::env;
14use std::path::PathBuf;
15
16fn main() {
17    // Tell cargo to look for shared libraries in the specified directory
18    println!("cargo:rustc-link-search=/path/to/lib");
19
20    // Tell cargo to tell rustc to link the system bzip2
21    // shared library.
22    println!("cargo:rustc-link-lib=bz2");
23
24    // The bindgen::Builder is the main entry point
25    // to bindgen, and lets you build up options for
26    // the resulting bindings.
27    let bindings = bindgen::Builder::default()
28        // The input header we would like to generate
29        // bindings for.
30        .header("wrapper.h")
31        // Tell cargo to invalidate the built crate whenever any of the
32        // included header files changed.
33        .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
34        // Finish the builder and generate the bindings.
35        .generate()
36        // Unwrap the Result and panic on failure.
37        .expect("Unable to generate bindings");
38
39    // Write the bindings to the $OUT_DIR/bindings.rs file.
40    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
41    bindings
42        .write_to_file(out_path.join("bindings.rs"))
43        .expect("Couldn't write bindings!");
44}
45```
46
47Now, when we run `cargo build`, our bindings to `bzip2` are generated on the
48fly!
49
50[There's more info about `build.rs` files in the Cargo documentation.][build-rs]
51
52[build-rs]: https://doc.rust-lang.org/cargo/reference/build-scripts.html
53