cbindgen generates C headers from Rust code, letting C or mixed-language projects use exported Rust libraries without manually maintaining matching declarations. section 8.5
To generate a header:
- Mark exported functions extern "C" and #[unsafe(no_mangle)], and give shared types a fixed repr. section 8.5.3
- Configure cbindgen.toml with language = "C", then run cbindgen manually to inspect the output. section 8.5.3
- For automatic regeneration, invoke cbindgen from build.rs and add it as a build dependency. section 8.5.4
Exporting a checksum function
A no_std Rust checksum function can accept a byte pointer and length; cbindgen generates a C declaration using uint8_t and uintptr_t. A null check alone does not prove the pointer is valid for the given length, so the function must document its safety contract. section 8.5.3
// build.rs
use std::env;
fn main() {
let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let config = cbindgen::Config::from_file("cbindgen.toml")
.expect("Unable to read cbindgen.toml");
cbindgen::Builder::new()
.with_crate(crate_dir)
.with_config(config)
.generate()
.expect("Unable to generate C bindings")
.write_to_file("embedded_rust_lib.h");
}
Example build.rs code that generates the header during the build. section 8.5.4
