Sub topic 13
Generating bindings with bindgen
This chapter assumes you can write extern blocks by hand, use #[repr(C)], and write a build.rs that compiles C with the cc crate. It also assumes you know how to wrap raw calls in a safe Rust type. Here you will let a tool write the declarations instead, and then check them.
Why generate bindings
Writing declarations by hand works for two functions. It does not work for a library with 300 functions, nested structs, enums, and typedefs. A mistake in a hand-written declaration is not caught by the compiler. If a field has the wrong type or the wrong order, the program compiles and then reads garbage.
bindgen reads a C header with libclang and emits Rust code. The code includes extern declarations, #[repr(C)] structs, type aliases, and constants. The header is the single source of truth, so the Rust side cannot drift from it.
bindgen does not make the library safe. Its output is a raw, unsafe layer. You still write the safe API on top.
Running the command line tool
Install the CLI and point it at a header. This is the quickest way to see what bindgen produces.
cargo install bindgen-cli
bindgen src/wrapper.h -o src/bindings.rsThe CLI needs libclang on your machine. On Debian or Ubuntu, install libclang-dev. On macOS, Xcode's command line tools are enough. If clang needs include paths or defines, pass them after --:
bindgen src/wrapper.h -o src/bindings.rs -- -Isrc -DUSE_FEATURE_XGiven the point.h header from earlier in this tutorial, with a wrapper.h that contains #include "point.h", the output looks like this. The exact text varies by bindgen version.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct point {
pub x: f64,
pub y: f64,
}
unsafe extern "C" {
pub fn point_distance(a: *const point, b: *const point) -> f64;
}Depending on the version, you will also see generated tests that assert size_of and align_of for each struct. Those tests compare the Rust layout with the layout clang computed, so keep them.
Running bindgen from build.rs
A checked-in bindings.rs goes stale when the header changes. It also bakes in the platform it was generated on. For a library that ships its own C code, regenerate the bindings during the build instead.
Add both tools to Cargo.toml:
[build-dependencies]
bindgen = "0.71"
cc = "1"Create src/wrapper.h, a small header that includes everything you want bound:
#include "point.h"Then extend build.rs:
use std::env;
use std::path::PathBuf;
fn main() {
cc::Build::new().file("src/point.c").compile("point");
println!("cargo:rerun-if-changed=src/point.c");
println!("cargo:rerun-if-changed=src/point.h");
let bindings = bindgen::Builder::default()
.header("src/wrapper.h")
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.allowlist_function("point_.*")
.allowlist_type("point")
.generate()
.expect("bindgen failed to generate bindings");
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is set by Cargo"));
bindings
.write_to_file(out_dir.join("bindings.rs"))
.expect("could not write bindings.rs");
}CargoCallbacks prints cargo:rerun-if-changed lines for the header and every header it includes, so Cargo reruns the script when they change. The explicit rerun-if-changed lines for the C files cover the compiled sources.
The generated file lands in OUT_DIR, not in your source tree. Include it from src/lib.rs:
#[allow(non_camel_case_types, non_snake_case, non_upper_case_globals, dead_code)]
mod sys {
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}
#[derive(Clone, Copy, Debug)]
pub struct Point {
pub x: f64,
pub y: f64,
}
pub fn distance(a: Point, b: Point) -> f64 {
let a = sys::point { x: a.x, y: a.y };
let b = sys::point { x: b.x, y: b.y };
unsafe { sys::point_distance(&a, &b) }
}The #[allow] attribute sits on the sys module only. Generated C names rarely follow Rust naming rules, and the warnings would otherwise bury your own. Keeping the output in a private sys module also stops raw pointers from leaking into your public API.
The data flow looks like this:
Controlling what gets generated
A header that includes <stdio.h> or <stdint.h> pulls hundreds of declarations into your output. By default bindgen generates bindings for everything it sees. Allowlists restrict the output to what you use.
| Method | Effect |
|---|---|
| `allowlist_function("regex")` | Keep only matching functions and the types they need |
| `allowlist_type("regex")` | Keep matching types and the types they depend on |
| `allowlist_var("regex")` | Keep matching global variables and `#define` constants |
| `blocklist_type("name")` | Skip a type, so you can supply your own definition |
| `opaque_type("name")` | Generate a blob of bytes with the right size, hiding the fields |
| `derive_default(true)` | Add `Default` to generated structs |
| `newtype_enum("regex")` | Generate C enums as newtype structs with associated constants |
The patterns are regular expressions that must match the whole name. Use point_.*, not point_.
Two options deserve explanation.
Opaque types. If the C API only passes counter * around and never exposes the fields, use opaque_type. You avoid depending on a layout you do not control. Bindgen will not generate Copy for such a type, which is what you want for a handle.
Enums. C lets any integer value sit in an enum variable. A Rust enum with an unlisted value is undefined behavior. The default output, constants plus an integer type alias, is safe. newtype_enum is also safe and reads better. Avoid rustified_enum for values that come from C, because a library that returns a new value in a later version causes undefined behavior in your program.
Reviewing the output
Treat generated code as a draft that a human must read once. Look for these points.
- Pointer mutability. C
constis reflected as*const. If the header omitsconston a read-only parameter, you get*mutand your wrapper must still be correct. - Ownership. Nothing in a header says who frees a returned pointer. Read the library's documentation and encode the answer in your wrapper, as in the earlier chapters on handles and
Drop. - Nullability. A
*const c_charreturn might be null. Bindgen cannot know, so check it in the wrapper. - Integer types.
int,long, andsize_tmap toc_int,c_long, andusize.longis 32 bits on 64-bit Windows and 64 bits on 64-bit Linux, so avoid casting these types to fixed-width ones without thinking. - Unions and bitfields. Bindgen supports them, but the accessors are awkward and often unsafe. Wrap them in small methods.
- Inline functions and macros. A
static inlinefunction in a header has no symbol to link against, and a function-like macro is not a function. Bindgen skips both by default. For inline functions you can callwrap_static_fns(true), which generates a C file you must compile. For macros, write a small C function that calls the macro and bind that.
Keeping bindings portable
Bindings generated on your laptop reflect your laptop's headers and target. Two practices reduce surprises.
- If you check in a generated file, regenerate it per target, or keep it only for a single supported platform and say so in the crate documentation.
- For a library found on the system, generate during the build so clang sees the headers actually installed. The
pkg-configcrate can supply the include paths, which you then pass with.clang_arg("-I/path").
When cross-compiling, bindgen needs to know the target. It reads TARGET from Cargo and passes it to clang. If the headers come from a sysroot, add .clang_arg("--sysroot=/path").
Common errors
- "Unable to find libclang". Install libclang, or set the
LIBCLANG_PATHenvironment variable to the directory that contains it. fatal error: 'foo.h' file not found. Clang cannot find an included header. Add.clang_arg("-Ipath")to the builder.- Unresolved symbol at link time. Bindgen declared a function, but nothing supplied it. Bindgen only writes declarations. You still need
ccto compile the C file, orcargo:rustc-link-libfor a system library. - Hundreds of unrelated items in
bindings.rs. You did not use allowlists. Add them. - Type name collisions. Two headers define the same name. Use
blocklist_typeor aparse_callbacksimplementation to rename an item. - Rebuild never happens. You forgot
CargoCallbacksandrerun-if-changed, so Cargo does not notice header edits.
Summary of the workflow
- Write a small
wrapper.hthat includes only the headers you need. - Run the CLI once to see the output, then move to
build.rs. - Add allowlists until the output contains only what you use.
- Read the output against the checklist above.
- Put the generated code in a private
sysmodule and write the safe API on top.
Exercise
Your build script runs bindgen on a header that includes <stdio.h>. The generated bindings.rs has thousands of lines, and one function you call, logmessage, shows up as `*mut cchar` where the C documentation says the string is never modified. What two changes would you make, and which part of the fix can bindgen not do for you?
Show answer
Add .allowlist_function("log_message") (and an allowlist for any types you use) so that only the functions you need are generated and the stdio.h declarations disappear. Then fix the pointer type in your safe wrapper: the header lacks const, so bindgen produces *mut c_char. Accept a &CStr in the safe function and pass s.as_ptr() as *mut c_char, which is sound only because the documentation says the C code does not write through it. Bindgen cannot decide that for you, because the header says nothing about whether the function modifies the buffer. A person has to read the documentation and take responsibility for that claim.