Sub topic 6
Linking against C libraries
An extern block tells the Rust compiler that a function exists. It does not tell the linker where the function lives. This chapter covers how a Rust program finds the machine code for the C functions it declares, and what goes wrong when it can't.
This chapter assumes you can write unsafe extern "C" declarations and call them (see "Declaring and calling C functions"), and that you know how a Cargo project is laid out. You don't need to know how a linker works internally. The chapter explains the parts you need.
Declaring is not linking
Compiling a Rust crate produces object code in which every foreign call is an unresolved symbol, such as strlen or point_distance. The linker joins this object code with libraries and fills in each symbol's address. If it can't find a symbol, the build fails.
The first example in this tutorial called abs and strlen without any linking setup. That works because every Rust program on common platforms already links the C standard library, so those symbols resolve for free. Any other library needs an explicit request.
Asking for a library with #[link]
The #[link] attribute names the library an extern block needs. This example calls cos from the C math library:
use std::ffi::c_double;
#[link(name = "m")]
unsafe extern "C" {
fn cos(x: c_double) -> c_double;
}
fn main() {
let value = unsafe { cos(0.0) };
println!("{value:.1}");
}The program prints 1.0. name = "m" becomes the linker flag -lm, which means "search for libm". You always give the bare name. Leave out the lib prefix and the file extension.
The example works on Linux and macOS. On Windows with the MSVC toolchain there is no separate math library, so #[link(name = "m")] fails there. Platform differences like this are a main reason to move linking into a build script, shown later.
A second example links against zlib and reads its version string:
use std::ffi::{c_char, CStr};
#[link(name = "z")]
unsafe extern "C" {
fn zlibVersion() -> *const c_char;
}
fn main() {
let version = unsafe { CStr::from_ptr(zlibVersion()) };
println!("zlib {}", version.to_str().unwrap());
}This needs the zlib development files on your machine. On Debian or Ubuntu, install zlib1g-dev. The linker looks for libz.so or libz.a, and the development package is what provides that unversioned file.
Static and dynamic linking
A library comes in two forms, and the form changes what ships with your program.
- A static library (
libfoo.a, orfoo.libon Windows) is an archive of object code. The linker copies the parts you use into your executable. The result has no runtime dependency on the library. - A shared library (
libfoo.so,libfoo.dylib, orfoo.dll) stays a separate file. The executable only records its name. The operating system's loader finds and maps the file each time the program starts.
You can choose the form with the kind option:
use std::ffi::c_int;
#[link(name = "point", kind = "static")]
unsafe extern "C" {
fn point_count() -> c_int;
}The point_count function is hypothetical. The syntax is the point here. The kinds you will meet most often:
| Kind | Meaning | Typical use |
|---|---|---|
| `dylib` | Link a shared library. This is the default when you give no kind. | System libraries such as `z` or `ssl` |
| `static` | Link a static archive and copy it into the output. | Libraries you build yourself, or want to ship inside one binary |
| `framework` | Link a macOS framework. | Apple system APIs |
| `raw-dylib` | Link a Windows DLL without an import library. | Windows system DLLs without needing the Windows SDK's `.lib` files |
If you give no kind, the compiler picks the default, which is dylib. If only a static archive exists, the build can fail with a "cannot find -lfoo" error. Naming kind = "static" makes the intent explicit.
Telling the linker where to look
The linker searches a fixed list of directories. System libraries in /usr/lib or /usr/lib/x86_64-linux-gnu are found automatically. A library anywhere else needs a search path, and #[link] cannot supply one. Paths are machine specific, so they don't belong in source code. The standard solution is a build script that prints instructions for Cargo:
// build.rs
use std::env;
fn main() {
println!("cargo:rerun-if-env-changed=POINT_LIB_DIR");
if let Ok(dir) = env::var("POINT_LIB_DIR") {
println!("cargo:rustc-link-search=native={dir}");
}
println!("cargo:rustc-link-lib=static=point");
}Each cargo: line on standard output is a message to Cargo:
cargo:rustc-link-search=native=DIRaddsDIRto the library search path.cargo:rustc-link-lib=static=pointlinkslibpoint.a. Without thestatic=part, it links dynamically.cargo:rerun-if-env-changed=NAMEreruns the script when that variable changes.
Newer Cargo versions also accept a double-colon form, cargo::rustc-link-lib=.... The single-colon form still works and is understood by older toolchains.
With this script, the extern block no longer needs #[link]. Keeping the library name in one place avoids conflicting settings. Run POINT_LIB_DIR=/opt/point/lib cargo build to point the build at a custom install.
The next chapter shows how the cc crate compiles C source and emits these lines for you.
Finding system libraries with pkg-config
Hard-coding paths breaks across distributions. On Unix systems, most libraries ship a .pc file that records the correct flags, and the pkg-config crate reads it. Add it to Cargo.toml:
[build-dependencies]
pkg-config = "0.3"Then probe for the library in build.rs:
// build.rs
fn main() {
pkg_config::Config::new()
.atleast_version("1.2")
.probe("zlib")
.expect("zlib 1.2 or newer was not found by pkg-config");
}probe runs the pkg-config tool, then prints the matching rustc-link-search and rustc-link-lib lines for you. A version check gives a clear error at build time instead of an obscure one at run time. On a machine without pkg-config or the .pc file, the build stops with your message. That failure is useful, because it names the missing package.
Cargo's links key
A package that wraps a native library should declare it in Cargo.toml:
[package]
name = "point-sys"
version = "0.1.0"
edition = "2024"
links = "point"
build = "build.rs"The links key tells Cargo that this package links the native library point. Cargo allows only one package per dependency graph to claim a given name, so two crates can't both link different copies of the same library into one binary. The key also lets a build script pass information to dependent crates through cargo:KEY=VALUE lines. By convention, crates that only expose raw declarations are named with a -sys suffix, such as libz-sys, and a safe wrapper crate depends on them.
Common errors and how to read them
The error message tells you which stage failed.
| Message | Stage | Usual cause |
|---|---|---|
| `undefined reference to 'foo'` or `undefined symbol: _foo` | Link time | No `#[link]` or build-script line, a typo in the symbol name, or a library listed in the wrong order |
| `cannot find -lfoo` or `library not found for -lfoo` | Link time | The library file isn't on the search path, or only the runtime package is installed and the `-dev` package is missing |
| `error while loading shared libraries: libfoo.so.1` | Run time | The program linked fine, but the loader can't find the shared file |
| A crash or wrong values with no link error | Run time | The declaration doesn't match the C signature |
Several of these have details worth knowing.
- Order matters for static libraries. The linker reads archives left to right and pulls in only the objects needed for symbols it has already seen. If
libA.acalls intolibB.a, emit therustc-link-libline forAbefore the one forB. - Run-time failures need a search path. Set
LD_LIBRARY_PATHon Linux (DYLD_LIBRARY_PATHon macOS) to the library's directory. For a lasting fix, emitcargo:rustc-link-arg=-Wl,-rpath,/opt/point/libfrom the build script, or link statically. - The linker does not check types. A C symbol is only a name. If you declare
fn point_distance(a: *const Point) -> f64but the C function takes two pointers, the build succeeds and the call reads garbage. The compiler can't catch this, so check each declaration against the header, or generate declarations with bindgen as covered later. - Unused declarations are discarded. A declared function you never call doesn't produce a link error. A missing symbol appears only once code uses it.
- C++ names are mangled. A C++ function not wrapped in
extern "C"has a compiler-generated symbol name that your declaration can't match. Wrap it in a C interface first. When the C name differs from the Rust name you want, use#[link_name = "real_c_name"]on the declaration.
Choosing a linking strategy
Use these criteria when you decide:
- System library present on every target machine (zlib, libm): link dynamically and probe with
pkg-config. Your binary stays small and gets security fixes when the system updates. - Library you ship yourself: compile it in the build script and link statically. The result has no external dependencies.
- Library with many platform variants: use a
-syscrate that handlespkg-configfirst and falls back to building the bundled source.
The trade-off is control against convenience. Static linking gives reproducible binaries but makes you responsible for updating the library. Dynamic linking offloads updates to the system but adds a run-time requirement.
Exercise
A Rust program declares unsafe extern "C" { fn compress_data(src: *const u8, len: usize) -> i32; } for a library in /opt/fastz/lib/libfastz.so. The build fails with undefined reference to 'compress_data'. Name two things the build script must tell Cargo to fix this, and give the Cargo output line for each. After the build succeeds, the program fails at startup with error while loading shared libraries: libfastz.so. What is that failure, and how can you fix it?
Show answer
The build script must add the directory to the search path with println!("cargo:rustc-link-search=native=/opt/fastz/lib"); and request the library with println!("cargo:rustc-link-lib=fastz");. The second failure happens at run time, not link time. The linker found the library, but the loader can't find the shared file when the program starts. Fix it by setting LD_LIBRARY_PATH=/opt/fastz/lib, by emitting cargo:rustc-link-arg=-Wl,-rpath,/opt/fastz/lib from the build script, or by linking a static libfastz.a instead.
Exercise
Your declaration says fn point_distance(a: *const Point) -> f64;, but the C function takes two const point * parameters. The program builds and links without errors. Why didn't the linker report the mismatch?
Show answer
The linker matches symbol names only. A C object file records the name point_distance and no parameter types, so any declaration with that name resolves. Calling the function with one argument leaves the second pointer as whatever value happens to be in its register or stack slot, which is undefined behavior. Prevent this by checking each declaration against the C header or by generating it with bindgen.