Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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: