Use a build.rs script to print linker flags that tell Cargo where to find your C library and which symbols to link.
- Create a
build.rsfile in your crate root to define the library name and path. - Add
println!("cargo:rustc-link-lib=static=your_lib_name");to specify the library to link. - Add
println!("cargo:rustc-link-search=native=/path/to/lib");to point to the directory containing the.aor.sofile. - 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();
}
}