Linking

2 Posts

build.rs, link, and pkg-config

5 minute

In FFI, declaring the C function is only the first step:

unsafe extern "C" {
    fn sensor_read(out: *mut u8, len: usize) -> i32;
}

This only tells Rust that a C ABI function named sensor_read exists.

The linker still needs to know:

which library contains this function?
where is the library file?
what other dependent libraries are needed?
during cross compilation, are these target libraries or host libraries?

C projects usually handle this with Makefiles, CMake, pkg-config, sysroots, and cross toolchains. Rust projects use #[link], build.rs, and build dependencies for the same job.

Read More

FFI: Letting Rust Call C

6 minute

Calling C from Rust can look like just writing an extern "C" declaration.

The real issue is different: a C function does not carry Rust’s borrowing, lifetime, Result, or destructor rules. Rust can call it, but the compiler cannot prove that the call satisfies the C API contract.

A better model is:

safe Rust API
-> validate and prepare arguments
-> call C inside a small unsafe block
-> convert error codes, output parameters, and raw pointers back to Rust types

The C header is the entry point

Suppose an existing C library exposes this header:

Read More