Compiling C with the cc Crate
Plenty of Rust crates contain C: compression libraries, crypto primitives, SQLite, platform glue. The standard way to build that C code is a build script using the cc crate, which finds the right C compiler for the target, passes sensible flags, builds a static library into OUT_DIR and tells Cargo how to link it. (Build Fundamentals: Static Libraries explains what happens underneath.)
The pieces
crc/
├── Cargo.toml [build-dependencies] cc = "1"
├── build.rs cc::Build::new().file(...).compile("checksum")
├── csrc/
│ ├── checksum.h
│ └── checksum.c
└── src/main.rs unsafe extern "C" { fn adler32(...) -> u32; }A working example
cargo new crc --vcs none -q
cd crc
mkdir csrc
cat > csrc/checksum.h <<'C'
#include <stddef.h>
#include <stdint.h>
uint32_t adler32(const uint8_t *data, size_t len);
C
cat > csrc/checksum.c <<'C'
#include "checksum.h"
uint32_t adler32(const uint8_t *data, size_t len) {
uint32_t a = 1, b = 0;
for (size_t i = 0; i < len; i++) {
a = (a + data[i]) % 65521;
b = (b + a) % 65521;
}
return (b << 16) | a;
}
C
cat > build.rs <<'RS'
fn main() {
println!("cargo::rerun-if-changed=csrc");
cc::Build::new()
.file("csrc/checksum.c")
.include("csrc")
.warnings(true)
.compile("checksum"); // -> libchecksum.a in OUT_DIR, linked statically
}
RS
cargo add --build cc 2>&1 | grep 'Adding cc v'
cat > src/main.rs <<'RS'
unsafe extern "C" {
fn adler32(data: *const u8, len: usize) -> u32;
}
/// Safe wrapper: the only place that touches the C function.
fn checksum(bytes: &[u8]) -> u32 {
unsafe { adler32(bytes.as_ptr(), bytes.len()) }
}
fn main() {
println!("adler32(\"Wikipedia\") = {:#010x}", checksum(b"Wikipedia"));
}
RS
cargo run 2>&1 | grep -v Unpacking
echo "--- what the build script produced"
find target/debug/build -name 'libchecksum.a'
grep -E '^cargo:+rustc-link' target/debug/build/crc-*/output Adding cc v1.10.0 to build-dependencies
Compiling find-msvc-tools v0.1.15
Compiling shlex v2.0.1
Compiling cc v1.10.0
Compiling crc v0.1.0 (/home/learner/crc)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.63s
Running `target/debug/crc`
adler32("Wikipedia") = 0x11e60398
--- what the build script produced
target/debug/build/crc-864a62cb6f546bbb/out/libchecksum.a
cargo:rustc-link-lib=static=checksum
cargo:rustc-link-search=native=/home/learner/crc/target/debug/build/crc-864a62cb6f546bbb/out
0x11e60398 is the well-known Adler-32 of "Wikipedia", so the C code ran correctly. The build script's saved output file shows what cc told Cargo: link the static library checksum, found in OUT_DIR. (cc uses the legacy single-colon cargo: syntax so it works with old compilers; both forms mean the same.)
What cc decides for you
| Concern | What cc does |
|---|---|
| which compiler | CC_<target>, CC, then the conventional name for the target (cc on the host, aarch64-linux-gnu-gcc for an ARM Linux target) |
| flags | -O and -g from the profile's OPT_LEVEL/DEBUG, -fPIC, target flags; plus CFLAGS/CFLAGS_<target> from the environment |
| archiver | AR, then the target's ar |
| rerun | prints rerun-if-env-changed for every variable it reads |
| parallel compiles | with its parallel feature, uses Cargo's jobserver |
So the same build script works for a native build and a cross-compile without changes: cargo build --target aarch64-unknown-linux-gnu makes cc call the ARM cross compiler.
Useful Build methods: .files(iter), .include(dir), .define("NAME", Some("1")), .flag("-mavx2") / .flag_if_supported(...), .std("c11"), .cpp(true) for C++ (links the C++ standard library), .opt_level(n).
Linking an existing system library
When the C library is already installed (a -dev package, a vendor SDK), there's nothing to compile; the build script only tells Cargo what to link. The usual tool is the pkg-config crate, which reads .pc files; the bare directives look like this:
// build.rs for a crate wrapping a system libfoo
fn main() {
println!("cargo::rustc-link-search=native=/opt/foo/lib");
println!("cargo::rustc-link-lib=foo"); // dylib by default: -lfoo
println!("cargo::rerun-if-env-changed=FOO_DIR");
}-sys crates and the links key
By convention, a crate that builds or links a native library is called <name>-sys and contains only the unsafe declarations. A safe wrapper crate (<name>) builds on it. The -sys crate declares links = "<name>" in [package], which does two things:
- Cargo refuses two packages with the same
linksvalue in one build, because two copies of a C library with the same symbols would clash at link time. - The build script can pass data to the build scripts of crates that depend on it directly:
cargo::metadata=KEY=VALUEbecomesDEP_<LINKS>_<KEY>in their environment.
cargo new --lib adler-sys --vcs none -q
cd adler-sys
mkdir include
echo 'unsigned adler_version(void);' > include/adler.h
echo 'unsigned adler_version(void) { return 3; }' > adler.c
cargo add --build cc -q
cat > build.rs <<'RS'
fn main() {
println!("cargo::rerun-if-changed=adler.c");
cc::Build::new().file("adler.c").compile("adler");
let inc = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("include");
println!("cargo::metadata=include={}", inc.display());
}
RS
sed -i 's/^edition = .*/&\nlinks = "adler"/' Cargo.toml
echo 'unsafe extern "C" { pub fn adler_version() -> u32; }' > src/lib.rs
cd ..
cargo new app --vcs none -q
cd app
echo 'adler-sys = { path = "../adler-sys" }' >> Cargo.toml
cat > build.rs <<'RS'
fn main() {
// a wrapper crate would pass this include path to its own cc::Build
println!("cargo::warning=adler headers in {}", std::env::var("DEP_ADLER_INCLUDE").unwrap());
}
RS
echo 'fn main() { println!("adler C library version {}", unsafe { adler_sys::adler_version() }); }' > src/main.rs
cargo run 2>&1 | grep -v -e Unpacking -e Compiling -e Finished Locking 4 packages to highest Rust 1.99.1 compatible versions
warning: app@0.1.0: adler headers in /home/learner/adler-sys/include
Running `target/debug/app`
adler C library version 3
DEP_ADLER_INCLUDE reached app's build script, which is how real wrapper crates find the headers of a -sys crate they depend on (openssl-sys and libz-sys publish include and root this way).
Test yourself
What does cc::Build::new().file("csrc/checksum.c").compile("checksum") produce?
- A shared library in target/
- A static library libchecksum.a in OUT_DIR, plus link directives for Cargo
- An object file next to the C source
- A Rust module
Why should a -sys crate declare links = "name"?
- To download the C library
- So Cargo rejects two copies of the same native library in one build, and so its build script can pass metadata to dependents
- It's required for cc to work
- To enable dynamic linking
You cross-compile with --target aarch64-unknown-linux-gnu. Which C compiler does the cc crate use by default on Linux?
- The host
cc aarch64-linux-gnu-gcc- clang with --target
- None: cc only builds for the host