Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a Cargo package only have one library target?

According to its manual, Cargo packages can have multiple executable targets, but only one library target is allowed.

A package can contain zero or one library crates and as many binary crates as you’d like. There must be at least one crate (either a library or a binary) in a package.

Why is it limited to one? What are the reasons and benefits?

like image 432
eonil Avatar asked Feb 23 '19 15:02

eonil


People also ask

What is a Cargo package?

Cargo packaging means any method of containment for shipment, including cases, cartons, crates and sacks, but excluding large units such as intermodal containers, vans or similar devices.

What is crate in Cargo?

The Cargo book uses the term crate as an alias for package.

What does Cargo build -- Release do?

cargo build --release puts the resulting binary in target/release instead of target/debug . Compiling in debug mode is the default for development-- compilation time is shorter since the compiler doesn't do optimizations, but the code will run slower. Release mode takes longer to compile, but the code will run faster.


2 Answers

Cargo is primarily a package manager. Thus, the primary role of a package is to define a library.

When we use a crate as a dependency, we only specify the package name in our Cargo.toml. Since there can be at most one library, Cargo doesn't need you to specify which one to use. If it were allowed to define multiple libraries in the same package, then we'd need to specify a way to define dependencies between them, so you'd have two ways to declare dependencies (external packages vs. internal crates), making the system more complex.

On the other hand, adding a dependency that doesn't provide a library doesn't make sense, at least not with Cargo, since Cargo only cares about the library target in that context. Thus, there is no reason to limit the other types of targets (binaries, examples, tests, etc.) to one each.

like image 191
Francis Gagné Avatar answered Dec 17 '22 04:12

Francis Gagné


I would expect that a cargo package can only have one library target because a library crate is by definition a collection of items (functions, types, traits, macros, values, etc.) while a binary crate has only one externally visible thing, a main entry point. Consequently, while the library crate's name is merely the root module within an hierarchy, the binary crate's name is the only thing.

like image 31
George Avatar answered Dec 17 '22 05:12

George