Sub topic 7
Compiling your own C code with build.rs
The earlier chapters called C functions that were already on the system, such as abs and strlen from the C standard library. This chapter covers the other common case, where the C source lives in your own repository. Cargo does not compile C by default, so you add a build script that does it. The script runs before your crate is compiled, builds the C file into a static library, and tells Cargo to link it.
This chapter assumes you can read the #[repr(C)] and unsafe extern "C" declarations from the previous chapters. It also assumes you have a C compiler installed (gcc, clang, or MSVC) and know the basic Cargo layout.
What a build script is
A build script is a Rust file named build.rs at the root of a package, next to Cargo.toml. Cargo compiles it as a separate small program and runs it before it compiles the package itself. The script talks to Cargo through two channels:
- Environment variables that Cargo sets for it, such as
OUT_DIR(a directory where the script may write generated files) andTARGET(the platform you are building for). - Lines printed to standard output that start with
cargo:. Cargo reads these as instructions, for example "link this library" or "rerun me when this file changes".
The cc crate is a helper built on top of this. It finds the right C compiler for the target platform, runs it, packs the object files into a static library, and prints the cargo: lines needed to link that library.
Project layout
This chapter reuses the point library from the earlier C example. The package looks like this:
point-ffi/
├── Cargo.toml
├── build.rs
└── src/
├── lib.rs
├── point.c
└── point.hThe C files are the ones from the spine: point.h declares a point struct and point_distance, and point.c implements it with sqrt.
Declare the helper crate under [build-dependencies], not [dependencies]. Build dependencies are compiled for the machine running the build, and they are not linked into your final program.
[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");
}These two statements do the following:
cc::Build::new()creates a builder. It readsTARGET,OPT_LEVEL,DEBUG, andOUT_DIRfrom Cargo's environment, so the C code is built with the same optimization level as your Rust code..file("src/point.c")adds one source file. The path is relative to the package root, which is the build script's working directory..compile("point")runs the compiler, archives the result aslibpoint.a(orpoint.libwith MSVC) insideOUT_DIR, and prints the instructions that addOUT_DIRto the library search path and linkpointstatically. You do not write those linker lines yourself.- The
rerun-if-changedline tells Cargo to rerun the script only whensrc/point.cchanges.
The Rust side is the declaration you already know:
// src/lib.rs
#[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. If the C file compiles and links, the test passes.
What happens during cargo build
The build script runs once per build configuration that needs it, not once per source edit. Cargo caches the result and decides whether to rerun the script from the rerun-if-changed lines it printed last time.
Rerun rules and why they matter
If your script prints no rerun-if-* line at all, Cargo reruns it whenever any file in the package changes. That is safe but slow. As soon as you print one rerun-if-changed line, Cargo only watches the paths you listed. This leads to the most common mistake with cc.
Suppose point.c includes point.h, and you edit only the header. Your script lists only point.c, so Cargo does not rerun it, the C file is not recompiled, and your program silently uses the old layout. List every file the C code depends on:
// build.rs
fn main() {
cc::Build::new()
.file("src/point.c")
.include("src")
.compile("point");
println!("cargo:rerun-if-changed=src/point.c");
println!("cargo:rerun-if-changed=src/point.h");
println!("cargo:rerun-if-changed=build.rs");
}Listing build.rs itself is a good habit, so that changes to the script trigger a rerun. You can also give a directory, and Cargo will watch the files in it.
Common builder options
cc::Build is a builder, so options chain. These are the ones you will use most:
| Method | Effect |
|---|---|
| `.file(path)` / `.files(iter)` | Add one source file, or many. |
| `.include(dir)` | Add a header search directory (`-I`). |
| `.define("NAME", Some("1"))` | Define a preprocessor macro (`-DNAME=1`). |
| `.flag_if_supported("-Wall")` | Add a flag only if the compiler accepts it. |
| `.warnings(true)` | Enable the compiler's default warning set. |
| `.std("c11")` | Select the C language standard. |
| `.opt_level(2)` | Override the optimization level (normally inherited from Cargo). |
Prefer flag_if_supported over flag for anything compiler-specific. A plain .flag("-Wall") fails the build on MSVC, which does not understand it.
For a library with many files, pass an iterator:
// build.rs
fn main() {
let sources = ["src/point.c", "src/shape.c", "src/util.c"];
cc::Build::new()
.files(sources)
.include("src")
.std("c11")
.warnings(true)
.compile("geometry");
for path in sources {
println!("cargo:rerun-if-changed={path}");
}
println!("cargo:rerun-if-changed=src");
}The name passed to compile becomes the library name, so keep it unique among the libraries in your dependency tree.
Linking extra system libraries
The cc crate links only the library it built. If your C code calls into another library, you must say so. point.c calls sqrt, which lives in the math library. On many Linux targets the Rust standard library already pulls that in, but if the linker reports an undefined reference to sqrt, add the instruction yourself:
// build.rs (addition for platforms that need libm)
fn main() {
cc::Build::new().file("src/point.c").compile("point");
println!("cargo:rerun-if-changed=src/point.c");
if std::env::var("CARGO_CFG_TARGET_FAMILY").as_deref() == Ok("unix") {
println!("cargo:rustc-link-lib=m");
}
}The check reads CARGO_CFG_TARGET_FAMILY, not cfg!(unix). Inside a build script, cfg! describes the machine running the script, while the CARGO_CFG_* variables describe the target you are building for. These differ when you cross-compile.
Cross-compilation and environment overrides
Because cc reads TARGET, it picks a matching compiler without extra code. For aarch64-unknown-linux-gnu, it looks for aarch64-linux-gnu-gcc. Users can override its choices with environment variables, so you should not hard-code them in build.rs:
CCorCC_<target>selects the compiler, for exampleCC_aarch64_unknown_linux_gnu.CFLAGSorCFLAGS_<target>adds flags.ARselects the archiver.
If a build fails with a C error, run cargo build -vv. The double -v shows the exact compiler command line and the output of the build script, which is where cc reports why it failed.
Failure modes
- The script panics or returns a non-zero exit code. The whole build stops.
ccpanics with the compiler's error output when C compilation fails, and that is the intended way to fail. - "Failed to find tool" or "No such file" for
cc. No C compiler is installed, or a cross-compiler is missing. Install one, or setCC. - Undefined symbol at link time. Either the declared name does not match the C name (C has no name mangling, but
staticfunctions are not exported), or a dependency library is not linked. - Wrong results with no error. Often a stale build, or a
#[repr(C)]struct that no longer matches the header. Recheck the rerun lines first.
Exercise
You edit src/point.h to add a third field to the point struct, and you update the Rust struct to match. Your build.rs lists only cargo:rerun-if-changed=src/point.c. After cargo build, distance results are wrong, and there is no compiler error. What went wrong, and what is the fix?
Show answer
Cargo only watches the paths the script lists, so editing the header did not rerun build.rs. The old libpoint.a, compiled with the two-field struct, was linked against Rust code that uses the three-field layout, which is a layout mismatch and undefined behavior. The fix is to add println!("cargo:rerun-if-changed=src/point.h"); (and ideally one for build.rs itself), then rebuild. Running cargo clean -p point-ffi forces a rebuild right away.
Exercise
Why is cc listed under [build-dependencies] and not [dependencies], and why should build.rs read CARGO_CFG_TARGET_FAMILY instead of using cfg!(unix)?
Show answer
cc is only needed while the build script runs, on the machine doing the build, so it is a build dependency and is not linked into the final program. cfg!(unix) inside build.rs describes the host that runs the script, not the target being built. When cross-compiling, the two differ, so the script must read the CARGO_CFG_* variables that Cargo sets for the target.