bindgen generates Rust foreign-function interface (FFI) declarations from C headers. It parses types, functions, and constants, reducing the work of maintaining bindings for large C libraries. Unlike bindgen, cbindgen generates C headers from Rust code. section 8.5 section 8.5.1
Generated declarations do not make a language boundary safe by themselves. Rust and C must agree on types and layout, and calls to generated foreign functions still require unsafe code. section 8.0 section 8.5.2
// example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H
#include <stdint.h>
typedef struct {
uint32_t id;
int16_t value;
} ExampleStruct;
void process_example(ExampleStruct* ex);
#endif // EXAMPLE_H
This hardware abstraction header declares a struct and a function that takes a pointer to it. section 8.5.1
bindgen example.h \ --use-core \ --allowlist-type "ExampleStruct" \ --allowlist-function "process_example" \ --blocklist-function "strcpy" \ --blocklist-var "errno" \ -o example_bindings.rs \ -- -target thumbv7em-none-eabi
This command generates bindings for the example header. Install the command-line tool first with cargo install bindgen-cli; the bindgen crate is used by build scripts. section 8.5.1
The command's options control what gets generated and how the header is parsed:
- --use-core uses core rather than std, including core::ffi for C types. section 8.5.1
- The allowlists select the struct and function. The blocklists demonstrate exclusions, but have no effect on this particular header because it declares neither name. section 8.5.1
- -o names the output file. Arguments after -- go to libclang; specify the target so the header is parsed for the embedded target rather than the build host. section 8.5.1 section 8.5.2
For repeatable builds, add bindgen as a Cargo build dependency and run it from build.rs. Write the generated file to Cargo's OUT_DIR, not src/: writing into the source tree interferes with change detection. The build script can also tell the linker where to find the prebuilt C library and which library to link. section 8.5.2
mod example_bindings {
include!(concat!(env!("OUT_DIR"), "/example_bindings.rs"));
}
Include the generated file from OUT_DIR inside a module. Its declarations are then accessed through that module's path. section 8.5.2
let mut ex = example_bindings::ExampleStruct { id: 0, value: 0 };
// SAFETY: `ex` is a valid, initialized ExampleStruct; process_example
// only writes through the pointer, it doesn't retain it past the call.
unsafe {
example_bindings::process_example(&mut ex as *mut _);
}
Call the generated function in an unsafe block. The safety comment records the pointer and lifetime assumptions that must hold for this call. section 8.5.2

