Linking native C libraries
⚓ Rust 📅 2025-08-11 👤 surdeus 👁️ 11Hi. I have two packages. The first one is a lib that uses bindings for native C libary.
unsafe extern "C" {
fn add(a: i32, b: i32) -> i32;
}
pub fn safe_add(a: i32, b: i32) -> i32 {
unsafe { add(a, b) }
}
and the second one is exe that depends on this lib:
fn main() {
let result = rust_lib::safe_add(2, 3);
println!("The result of adding 2 and 3 is: {}", result);
}
I don't understand a few things:
- Why does the lib compile without any build.rs scripts with
cargo build? It looks like the compiler doesn't check that theaddfunction exists somewhere. - The exe compiles only if I add these build scripts:
// lib package
fn main() {
println!("cargo::rustc-link-lib=add");
}
// exe package
fn main() {
println!("cargo::rustc-link-search=native=<path/to/native/lib>");
}
Why does it work like this? I don't understand why I don't need to specify the library path in the lib's build script and the library name in the exe's build script. Do these build scripts depend on each other?
2 posts - 2 participants
🏷️ Rust_feed