Multiple binaries in cargo

I have a project that I want, when a certain feature is enabled, to compile additional binaries in addition to the main one.
I couldn't find any proper documentation on the subject. The only thing I could find is that I should use a [[bin]] section but I couldn't find how to use it.


The easiest way is letting cargo infer that a file is the entry point of a binary and so avoid the need to use [[bin]]:

Cargo will also treat any files located in src/bin/*.rs as executables.

Project Layout

If you want more control over the file structure, an explicit [[bin]] section works like:

name = "some-name"
path = "path/to/"

This is puzzling to me since I can't see how this is actually useful. If I try and add there any "mod _;" to code outside the bin directory, it wont recognize it (obviously, since it is in the folder above). So I know I can allow it to use it with #[path], but it is starting to feel more and more hacky and not so ergonomic. This feels like it's only useful for toy, simple, side binaries and not something that needs to share actual code with the main binary. I am probably missing something here.

Thank you, I was able to get this to work by having multiple [[bin]] elements. Not really knowing TOML too well I didn't realize I could have multiple [[bin]] entries.

Now I just need to understand how I can disable one based on features.

My use case is that I have a hex editor that by default has only a terminal UI, and if the gtk feature is enabled I want to build the gtk UI as well.

Thank you!

If I try and add there any "mod _;" to code outside the bin directory, it wont recognize it (obviously, since it is in the folder above)

For what it is worth, it is possible to access publicly exported modules in the src/ directory from src/bin/ by using:

extern crate crate_name;
use crate_name::mod_name;

This is also true when writing binaries in test/ and bench/ directories.


The recommended approach is to share code by putting it all in a library (i.e. src/, and having each binary call things from that.

Not sure that's possible at the moment, sadly.


That should pretty well in my case. It just feels weird that the ergonomics of multiple binaries is so different than a single one.

Should I open an issue for this on github.