4

In the Importing External Crates section of the Rust book the author creates main.rs file in an already existing library project. I randomly picked up a bunch of crates from crates.io, examined their structure and did not find any project containing both lib.rs and main.rs files. So i'm wondering if it is common to have both files in a library project hosted at crates.io or it should be considered a poor style?

To be more clear, I'm asking about developing a library designed to share with the community, not about an executable with a few days lifecycle. I'm aware of Cargo's testing capabilities, so the purpose of main.rs I want to add to the library is not testing. A good example of how my main.rs in the library crate should relate to the library is how curl command line tool is related to libcurl library. To my mind it is convenient to have a project for which cargo build builds an executable by default but all the functionality is available for importing as a library.

Sergey
  • 263

1 Answers1

5

The easiest way to create a crate which contains a binary and library (such as your curl and libcurl example) is to create a folder src/bin in your project and place your a file that will serve as the entry point to your binary there (must contain a fn main() {}). In your example this would be src/bin/curl.rs.

All of your "library" code would go in src/lib.rs (and additional modules).

Finally, you'd add a section to your Cargo.toml describing where to find the binary.

[[bin]]
name = "curl"

So the project layout would look like this (assuming we named the project curl-rs with cargo):

$ tree curl-rs
curl-rs
├── bin
│   └── curl.rs
├── Cargo.toml
└── src
    └── lib.rs

2 directories, 3 files

In order to use the functionality defined in our lib.rs it's the same as if using an external dep:

// in src/bin/curl.rs
extern crate curl;

fn main() {
    // Do stuff
}

Compiling this project will place a statically linked binary curl in target/{debug,release} as well as a libcurl.rlib which will be used if someone simply uses this project as a dep from something like crates.io.

kbknapp
  • 51