Structural differencebetween cargo --bin and --lib

Hi,

Just a question that is curiosity more than need:

if I create a crate with --lib and decide later on to make it an executable, the only thing I should modify is the lib.rs -> main.rs and everything should be ok ?

Conversely, from exec to lib, main.rs -> lib.rs and the crate is good to go ?

I saw no other difference when I tried. But..

Not that I need it, but I happened to forget to specify --lib in one crate this morning and decided to rm the tree and call the cargo init X --lib. On an empty tree, well, the solution is trivial, but once you add crates, and source, is there a catch to just modify the "entry" file name ?

Please note, I am not talking about the functionality difference between an executable and a lib, just the cargo file structure and management.

(let's not discuss the (in)sanity of not knowing in the first place what your code should be :slightly_smiling_face:)

Thanks

1 Like

Well, binary targets need a fn main(), but otherwise everything should be okay, yes. Note that it is completely fine to have a binary crate (or multiple binary crates) and a library crate in your package, i.e. src/main.rs and src/lib.rs can happily coexist together. If you are curious about Cargo packages and targets, you might want to check out the Cargo book, especially these pages:

5 Likes

The --lib project will have "Cargo.lock" in the ".gitignore" file.
The --bin project will not ignore "Cargo.lock" and track "Cargo.lock" with git.

2 Likes

Ok, I get it now,

Thanks a lot :+1: :saluting_face:

1 Like

This used to be the case but was recently changed: Change in Guidance on Committing Lockfiles | Rust Blog

With new versions of Cargo, the .gitignore files are identical.

4 Likes

Yeah, looks like it changed yesterday!

js@flower:~/temp$ cargo --version
cargo 1.73.0 (9c4383fb5 2023-08-26)
js@flower:~/temp$ cargo new --lib lib
     Created library `lib` package
js@flower:~/temp$ cargo new --bin bin
     Created binary (application) `bin` package
js@flower:~/temp$ diff -r lib/ bin/
diff -r lib/Cargo.toml bin/Cargo.toml
2c2
< name = "lib"
---
> name = "bin"
diff -r lib/.gitignore bin/.gitignore
2d1
< /Cargo.lock
Only in lib/src: lib.rs
Only in bin/src: main.rs

js@flower:~/temp$ rustup update
<SNIP>
js@flower:~/temp$ cargo --version
cargo 1.74.0 (ecb9851af 2023-10-18)
js@flower:~/temp$ cargo new --lib lib
     Created library `lib` package
js@flower:~/temp$ cargo new --bin bin
     Created binary (application) `bin` package
js@flower:~/temp$ diff -r lib/ bin/
diff -r lib/Cargo.toml bin/Cargo.toml
2c2
< name = "lib"
---
> name = "bin"
Only in lib/src: lib.rs
Only in bin/src: main.rs

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.