Sub topic 6
Linking against C libraries
This chapter assumes you can write an extern block and call a C function from unsafe code, and that you know the basics of Cargo. Declaring a function tells the compiler its signature. Linking is the step that finds its machine code. Without it, a correct declaration still fails to build.
Declaration versus linking
An extern block says "a function with this name and signature exists somewhere." It does not say where. The linker resolves the name after compilation. If it can't find the symbol, you get an error like this:
undefined reference to `point_distance'This is a link error, not a Rust type error. The fix is to tell the linker which library holds the symbol.
Libraries that are already linked
Rust programs on common platforms already link the C standard library. That is why abs and strlen work with no extra setup. Other libraries, such as libm for math or libz for compression, must be named explicitly.
The `#[link]` attribute
Put #[link(name = "...")] on the extern block to name the library. The name omits the lib prefix and the file extension.
use std::ffi::{c_double, c_int};
#[link(name = "m")]
unsafe extern "C" {
fn cbrt(x: c_double) -> c_double;
}
fn main() {
let r = unsafe { cbrt(27.0) };
println!("{r}");
}Here name = "m" makes the linker look for libm. The program prints 3.
By default the library is linked dynamically if a shared version exists. You can request a kind:
#[link(name = "z", kind = "dylib")]links a shared library.#[link(name = "z", kind = "static")]links a static library, which is copied into your binary.
Telling Cargo where to look
The linker searches standard system directories. When a library lives elsewhere, a build script can add a search path. Cargo reads lines that the script prints to standard output.
// build.rs
fn main() {
println!("cargo:rustc-link-search=native=/opt/mylib/lib");
println!("cargo:rustc-link-lib=mylib");
println!("cargo:rerun-if-changed=build.rs");
}The two rustc-link lines do the same job as #[link], but they live in the build script, so they can depend on the environment. A script can read environment variables or probe for installed libraries before it prints them.
| Mechanism | Where it lives | Best for |
|---|---|---|
| `#[link(name = "m")]` | Source code | Stable, well-known libraries |
| `cargo:rustc-link-lib` | `build.rs` | Names that depend on the environment |
| `cargo:rustc-link-search` | `build.rs` | Non-standard install paths |
Static or dynamic
The choice affects how you ship the program.
- A dynamic link keeps the library outside your binary. The library must be present on the machine that runs the program. Updates to the library apply without a rebuild.
- A static link copies the library code into your binary. The binary is larger but needs no matching library at run time.
Common errors
undefined referenceorunresolved external symbol. The library is not named, or the name is wrong. Checkname = "..."and remember to leave out thelibprefix.cannot find -lfoo. The linker knows the name but not the directory. Add arustc-link-searchline, or install the development package for the library.- Works on your machine, fails elsewhere. A dynamic library that you linked is missing on the target machine. Install it there, or link statically.
- Wrong symbol name. C names are case sensitive. Check the spelling against the C header.
Exercise
Your build fails with cannot find -lz, and your source has #[link(name = "z")]. What does the error mean, and what are two ways to fix it?
Show answer
The linker understood the name z but could not find libz in any directory it searches. Fix it by installing the development package that provides libz on that machine, or by adding a cargo:rustc-link-search=native=<dir> line in build.rs that points to the directory holding the library.
Exercise
You declare fn cbrt(x: c_double) -> c_double but forget #[link(name = "m")]. On a platform where libm is not linked by default, at which stage does the failure appear, and what is the message type?
Show answer
It appears at link time, after the Rust code compiles. The message is a linker error such as undefined reference to 'cbrt', not a Rust type error.