liveBook · Manning

Libc crate

As explained in Refactoring to Rust

The libc crate is a Rust library providing platform-specific bindings and type definitions for the C standard library and C-compatible primitives.

The libc crate supplies Rust bindings to the C standard library, including platform-aware types for C primitives such as c_char and c_int. Rust keeps these bindings outside its standard library because many programs do not need C interoperability. section 3.2

Use the crate when connecting Rust code to C functions:

  • Import C-compatible types with use libc::{c_char, c_int};. section 3.2.1
  • Represent a C function signature such as solve(char *, int *) as fn solve(line: *const c_char, solution: *mut c_int) -> c_int. section 3.2
  • Let Cargo download, compile, and link libc instead of configuring compiler flags and dependency steps manually. section 3.2.1

Adding libc to a Cargo package

Add libc = "0.2.80" beneath [dependencies] in Cargo.toml, then run cargo build. Cargo updates its registry index, compiles libc, and compiles the calculate crate. section 3.2.1

[package]
name = "calculate"
version = "0.1.0"
authors = ["You <you@you.com>"]
edition = "2018"

# See more keys and their definitions at
# https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libc = "0.2.80"

Inspect the complete Cargo.toml dependency entry for libc. section 3.2.1

How Refactoring to Rust covers it

How deep it goes
Defines platform-aware C primitive types and shows dependency inclusion, but stops short of implementing the foreign function.
Examples
Uses c_char, c_int, a solve function signature, Cargo.toml, and cargo build in a calculator package.
What it assumes
Assumes basic Rust and Cargo familiarity while teaching crates, dependencies, and C-compatible types incrementally.
What you can do after
Operate/configure Cargo to add libc and compile a Rust package using C-compatible types.
How it connects
Connects C FFI, the C standard library, Rust standard library, Cargo, and unsafe Rust.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.