Sub topic 7
Compiling your own C code with build.rs
This chapter assumes you know basic Cargo usage, can write an extern block, and have read the earlier chapters on #[repr(C)] structs and linking. You will compile a small C file as part of cargo build and call it from Rust.
Why a build script
The previous chapter linked against libraries that already exist on the system. When the C code lives in your own repository, someone has to compile it first. Cargo does not compile C. A build script fills that gap. It is a Rust program named build.rs at the package root. Cargo compiles and runs it before it builds your crate. The script can compile C files and print instructions that tell Cargo how to link the result.
The cc crate does the hard part. It finds a C compiler for the target platform, passes the right flags, produces a static library, and prints the link instructions for you.
Project layout
Use the point C library from the earlier example. The package looks like this:
point-ffi/
├── Cargo.toml
├── build.rs
└── src/
├── lib.rs
├── point.c
└── point.hCargo.toml
The cc crate is a build dependency, not a normal dependency. It is compiled for the build script only and is not linked into your final crate.
[package]
name = "point-ffi"
version = "0.1.0"
edition = "2024"
[build-dependencies]
cc = "1"The build script
// build.rs
fn main() {
cc::Build::new().file("src/point.c").compile("point");
println!("cargo:rerun-if-changed=src/point.c");
}compile("point") builds libpoint.a in Cargo's output directory. It also prints cargo:rustc-link-lib=static=point and the matching search path, so you do not write a #[link] attribute.
The rerun-if-changed line matters. Once a build script prints any rerun-if-changed line, Cargo reruns it only when a listed file changes. Without the line, Cargo reruns the script whenever any file in the package changes. Add a line for every file the build depends on, such as src/point.h.
Calling the library
C's math.h function sqrt comes from the math library. On Linux, a static library that calls sqrt may need -lm at the final link. Rust's standard library usually brings in libm on Linux, so the example links without extra work. If you see an undefined reference to a math function, add println!("cargo:rustc-link-lib=m"); to the script.
Now write src/lib.rs using the safe wrapper from the struct chapter, plus a test:
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Point {
pub x: f64,
pub y: f64,
}
unsafe extern "C" {
fn point_distance(a: *const Point, b: *const Point) -> f64;
}
pub fn distance(a: &Point, b: &Point) -> f64 {
unsafe { point_distance(a, b) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn three_four_five() {
let a = Point { x: 0.0, y: 0.0 };
let b = Point { x: 3.0, y: 4.0 };
assert_eq!(distance(&a, &b), 5.0);
}
}Run cargo test. The first run compiles point.c, then the crate, then the test binary.
Common errors
| Symptom | Likely cause |
|---|---|
| `failed to find tool "cc"` | No C compiler installed. Install `gcc`, `clang`, or the MSVC build tools. |
| `undefined reference to point_distance` | The function name in the `extern` block does not match the C name, or the file was not passed to `cc::Build`. |
| C edits are ignored | The `rerun-if-changed` path is wrong or missing a file. |
| `unresolved import cc` in `build.rs` | `cc` was added under `[dependencies` instead of `[build-dependencies]`. |
The cc crate also reads environment variables such as CC and CFLAGS. Cross compilation therefore works when you set CC to a compiler for the target.
Useful builder options
.include("src")adds a header search directory..define("NAME", "value")sets a preprocessor macro..flag_if_supported("-Wall")adds a flag only if the compiler accepts it..files(["a.c", "b.c"])compiles several sources into one library.
Exercise
You add src/helpers.h, which point.c includes, and change it. Cargo does not rebuild the C code. What do you add to build.rs, and why?
Show answer
Add println!("cargo:rerun-if-changed=src/helpers.h");. Once the script prints any rerun-if-changed line, Cargo reruns it only when a listed file changes. The header was not listed, so the change went unnoticed.
Exercise
Why is cc listed under [build-dependencies] and not [dependencies]?
Show answer
Only build.rs uses it, and build.rs runs before the crate is compiled. Your library or program never calls cc, so it should not be a runtime dependency.