Hello, I am quite new to Rust, who is reading the Rust Programming Book!
I got curious what is the difference between
cargo new --lib and
cargo new --bin.
More specifically, if once I create a new package using
cargo new --bin and later decided to add
src/lib.rs, I was not able to import contents in
extern crate <package name>.
However, the opposite way works very well.
What is the key difference that those packages created from
--lib flag and
--bin flag behave differently?
There isn’t any. The only differences are in the generated files (
The problem is that you can’t link to a binary crate because it’s a binary.
Thank you for your answer!
Then I have a different question, where are information that indicates a crate is a binary crate, is stored?
I have no idea how Rust distinguish between binary crates and library crates, if both has
lib.rs in the
I looked at
Cargo.toml, but I couldn;t see any differences.
It’s implied by the source files. If there’s a
src/main.rs, that is compiled as a binary. If there’s a
src/lib.rs, that is compiled as a library. Each
src/bin/*.rs is compiled as a binary.
You can be explicit about this, which is explained in the Cargo documentation.
So there are rules that Rust determines the crate type from the project layout.
I will take a look at the document.
Thanks a lot!