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 13extern crate bindgen; 14 15use std::env; 16use std::path::PathBuf; 17 18fn main() { 19 // Tell cargo to look for shared libraries in the specified directory 20 println!("cargo:rustc-link-search=/path/to/lib"); 21 22 // Tell cargo to tell rustc to link the system bzip2 23 // shared library. 24 println!("cargo:rustc-link-lib=bz2"); 25 26 // Tell cargo to invalidate the built crate whenever the wrapper changes 27 println!("cargo:rerun-if-changed=wrapper.h"); 28 29 // The bindgen::Builder is the main entry point 30 // to bindgen, and lets you build up options for 31 // the resulting bindings. 32 let bindings = bindgen::Builder::default() 33 // The input header we would like to generate 34 // bindings for. 35 .header("wrapper.h") 36 // Tell cargo to invalidate the built crate whenever any of the 37 // included header files changed. 38 .parse_callbacks(Box::new(bindgen::CargoCallbacks)) 39 // Finish the builder and generate the bindings. 40 .generate() 41 // Unwrap the Result and panic on failure. 42 .expect("Unable to generate bindings"); 43 44 // Write the bindings to the $OUT_DIR/bindings.rs file. 45 let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); 46 bindings 47 .write_to_file(out_path.join("bindings.rs")) 48 .expect("Couldn't write bindings!"); 49} 50``` 51 52Now, when we run `cargo build`, our bindings to `bzip2` are generated on the 53fly! 54 55[There's more info about `build.rs` files in the crates.io documentation.][build-rs] 56 57[build-rs]: http://doc.crates.io/build-script.html 58