cbindgen: Auto-generate C/C++ Headers for Rust
cbindgen automatically generates C/C++ headers for your Rust code, saving you from writing tedious FFI boilerplate. Use it when exposing a Rust library to other languages. Its feature set is ad-hoc, so it may not support your specific edge case out of the box.
WHY IT EXISTS: Rust's safety and performance make it ideal for core libraries, but you often need to call that code from other languages like C, C++, or Python. Manually writing the C header files (.h) to define the interface is tedious, repetitive, and a common source of bugs when the Rust code and the header drift out of sync.
THE MENTAL MODEL: Think of cbindgen as a "translator" for your Rust library's public API. It reads your Rust source code, specifically the parts you've marked for export (like #[no_mangle] pub extern "C" fn), and writes the corresponding C or C++ header file that other languages can understand and use to call your functions.
HOW IT WORKS: cbindgen parses your Rust code, looking for functions, structs, and enums intended for a Foreign Function Interface (FFI). Based on this, it generates header file text that correctly represents Rust's types and function signatures in C/C++ syntax. It understands how Rust lays out data in memory and ensures the generated header reflects the stable C ABI. You can run it as a command-line tool or integrate it into your build process via a build.rs script.
WHEN TO USE IT: Use cbindgen whenever you are writing a Rust library that needs to be consumed by a non-Rust project. This is common for building high-performance components in Rust to be used in existing C/C++ codebases, or for creating native modules for languages like Python, Ruby, or Node.js. It ensures your C API remains consistent with your Rust implementation.
WHEN NOT TO USE IT: If your Rust project is a standalone application or a library only meant to be used by other Rust crates, you don't need cbindgen. It is specifically for creating C-compatible interfaces. For extremely simple APIs (one or two functions), manual creation is possible, but automation via cbindgen is better for long-term maintenance.
ONE CANONICAL EXAMPLE: Mozilla, the original author, uses cbindgen to integrate Rust components into Firefox's large C++ codebase. A Rust component for parsing URLs or rendering part of a web page can be written, and cbindgen will create the .h file that the C++ code includes to call the new, safe Rust functions.
Read the original → github.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.