liveBook · Manning

Cbindgen

As explained in Embedded Software with Rust

cbindgen is a tool that generates C and C++ header files from Rust source code.

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

How Embedded Software with Rust covers it

How deep it goes
Shows API-shaping requirements, configuration, manual generation, and build.rs automation through a checksum example.
Examples
Uses a no_std checksum function and its generated C declaration to illustrate pointer safety and type mapping.
What it assumes
Assumes exported functions use extern "C" and shared types have fixed repr; it does not establish those boundary rules.
What you can do after
Apply cbindgen to generate headers that C projects can use with a Rust static library.
How it connects
Contrasts with bindgen and relies on extern "C" functions and fixed-layout shared types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.