Introduction
cheadergen generates accurate C headers for Rust libraries that expose a C-compatible API.
cheadergen provides:
- Multi-crate support. One C header per crate, with
cross-crate
#includes wired up automatically. - Compiler-accurate type analysis. Type information comes from
rustdoc-json, so the generated output mirrors what the Rust compiler actually sees. - Macro-aware. Items defined by declarative or procedural macros are picked up automatically.
cheadergen is an alternative to
cbindgen. Check out our
comparison page
for more details.
What it does
You write Rust:
#![allow(unused)]
fn main() {
#[repr(C)]
pub struct Point {
pub x: f64,
pub y: f64,
}
#[unsafe(no_mangle)]
pub extern "C" fn distance(a: Point, b: Point) -> f64 {
((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt()
}
}
cheadergen produces a header your C code can consume:
typedef struct {
double x;
double y;
} Point;
double distance(Point a, Point b);
New to C/Rust interoperability?
If you’ve never written extern "C" in Rust before, the
FFI chapter of the Rust Nomicon
is a good primer on the building blocks cheadergen relies on: the C
calling convention, #[no_mangle] for stable symbol names, #[repr(C)]
for predictable struct layout, and the rules around passing data across
the boundary.
Read through it first if any of those terms feel unfamiliar: the
rest of this guide assumes you know what they do, and focuses on how
cheadergen can support your mixed C/Rust projects.
Author
cheadergen (C Header Generator) is built and maintained by Luca Palmieri.
User guide structure
This guide is structured as follows:
- Getting started. If you’re new, start here. Install the CLI, then walk through the Quickstart.
- Foundations. The load-bearing concepts you’ll meet using cheadergen: target packages, item annotations, and global configuration.
- How it works. The internals: the processing pipeline and generics and monomorphization.
- What you get. The shape of the generated output: anatomy of a generated header and bundled vs partitioned output.
- Limits and alternatives.
Comparison with
cbindgen, whatcheadergencan’t do, and C++ support. - How-to guides.
Recipes for common tasks:
wiring
cheadergeninto Cargo, generating headers across a workspace, migrating fromcbindgen, and more. - API references on docs.rs.
The canonical references for the options exposed by the
#[cheadergen::config(...)]attribute and thecheadergen.tomlconfig file.