23.10 Binary vs. Library Crates
Cargo distinguishes between packages that produce executable binary crates and those that produce library crates:
- Binary Packages/Crates: Compile to an executable file. They must have a
src/main.rs
file containing afn main()
function, which serves as the program’s entry point for the main binary crate.cargo new <name>
creates a binary package by default, containing one binary crate. - Library Packages/Crates: Compile to a Rust library file (
.rlib
or.dylib
) intended to be used as a dependency by other packages. They typically have asrc/lib.rs
file as their crate root.cargo new <name> --lib
creates a library package, containing one library crate.
A single package can contain both a library crate and one or more binary crates:
- Define the library crate in
src/lib.rs
. - Define the main binary crate in
src/main.rs
. - Define additional binary crates in
src/bin/another_bin.rs
,src/bin/yet_another.rs
, etc.
Cargo will build the library crate and all specified binary crates within the package. This pattern is common for packages that provide both a reusable library API and a command-line tool interface (as separate crates within the same package).