How to Link to C Libraries in Rust with build.rs

Link C libraries in Rust by printing linker flags in a build.rs script to specify the library name and search path.

Use a build.rs script to print linker flags that tell Cargo where to find your C library and which symbols to link.

  1. Create a build.rs file in your crate root to define the library name and path.
  2. Add println!("cargo:rustc-link-lib=static=your_lib_name"); to specify the library to link.
  3. Add println!("cargo:rustc-link-search=native=/path/to/lib"); to point to the directory containing the .a or .so file.
  4. Declare the external functions in your Rust code using extern "C" { fn your_function(); }.
// build.rs
fn main() {
    println!("cargo:rustc-link-lib=static=your_lib_name");
    println!("cargo:rustc-link-search=native=/usr/local/lib");
}

// src/lib.rs
extern "C" {
    fn your_function();
}

pub fn call_c() {
    unsafe {
        your_function();
    }
}