expression
Generate C declarations with bindgen
Bindgen reads a native header using Clang and creates Rust declarations. Restrict generation to the public API you intend to use. It does not supply the C implementation: the separate cc step compiles and links the reviewed local source. Cargo places generated files in OUT_DIR. This lab intentionally uses edition 2021 for compatibility with generated extern declarations; verify the generator’s edition support before migrating. Expected lab stdout (not executed): 42 Common mistake: Assuming a generated declaration supplies the native implementation or proves safety. This is part of a multi-file lab, not a standalone playground snippet.
Formal Syntax & Structure
rust syntaxrust
bindgen::Builder::default().header(...).allowlist_function(...).generate()Working Example
Example Snippetrust
fn main() { println!("cargo:rerun-if-changed=native/scale.h"); println!("cargo:rerun-if-changed=native/scale.c"); cc::Build::new().file("native/scale.c").compile("bm106_scale"); let bindings = bindgen::Builder::default() .header("native/scale.h") .allowlist_function("^bm106_scale$") .generate().expect("generate bindings"); let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")); bindings.write_to_file(out.join("bindings.rs")).expect("write bindings");}