Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I build multiple binaries with Cargo?

People also ask

Where does cargo build put binaries?

The . cargo/bin directory of your home directory is the default location of Rust binaries. Not only the official binaries like rustup , rustc , cargo , rustfmt , rustdoc , rls and also the binaries you can install via cargo install command, will be stored in this directory.

Where is cargo binary?

All binaries installed with cargo install are stored in the installation root's bin folder. If you installed Rust using rustup.rs and don't have any custom configurations, this directory will be $HOME/. cargo/bin. Ensure that directory is in your $PATH to be able to run programs you've installed with cargo install .

Does cargo run also build?

We can build a project using cargo build . We can build and run a project in one step using cargo run . We can build a project without producing a binary to check for errors using cargo check . Instead of saving the result of the build in the same directory as our code, Cargo stores it in the target/debug directory.


You can specify multiple binaries using [[bin]], as mentioned here:

[[bin]]
name = "daemon"
path = "src/daemon/bin/main.rs"

[[bin]]
name = "client"
path = "src/client/bin/main.rs"

Tip: If you instead put these files in src/bin/daemon.rs and src/bin/client.rs, you'll get two executables named daemon and client as Cargo compiles all files in src/bin into executables with the same name automatically. You need to specify names and paths like in the snippet above only if you don't follow this convention.


Another way is to use the workspace feature. This will provide more flexibility due to the fact that we can have more than one library. Example project structure:

.
├── Cargo.toml
├── cli
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── core
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
├── daemon
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── gui
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── rpc
    ├── Cargo.toml
    └── src
        └── lib.rs

Contents of the root Cargo.toml:

[workspace]
members = ["cli", "core", "daemon", "gui", "rpc"]

Another format could be to replicate what the Crates.io source code has done, if you have a massive project, something like:

Main Library in src, with a Bin folder with your executables. Then make calls to your main library crate from your executables.

That way you library is centralized so easier to find things as it's cached.