Add libc to Cargo.toml and import functions with use statements to call C library APIs from Rust.
You use the libc crate by adding it as a dependency in Cargo.toml and importing its types or functions with a use statement in your source code.
[dependencies]
libc = "0.2"
use std::ffi::CString;
fn main() {
let msg = CString::new("Hello from libc!\n").unwrap();
unsafe {
libc::printf(msg.as_ptr());
}
}
The libc crate provides Rust bindings to the standard C library, allowing you to call low-level system functions directly. You use it when you need to interact with the operating system in ways that Rust's standard library doesn't support, like calling specific C APIs. Think of it as a bridge that lets your Rust code speak the language of the underlying C system.