5

I am trying to build a single Rust binary executable. In the src directory I have four files:

main.rs:

use fasta_multiple_cmp::get_filenames;

fn main() {
    get_filenames();
}

mod.rs:

pub mod fasta_multiple_cmp;

pub mod build_sequences_matrix;

fasta_multiple_cmp.rs:

pub mod fasta_multiple_cmp {

...

    pub fn get_filenames() {
    let args: Vec<String> = env::args().collect();
    ...

build_sequences_matrix.rs:

pub mod build_sequences_matrix {

    use simple_matrix::Matrix;
    ...

Cargo told me:

src/main.rs:3:5 | 3 | use fasta_multiple_cmp::get_filenames; | ^^^^^^^^^^^^^^^^^^ use of undeclared crate or module `fasta_multiple_cmp

I believed I understood some little things, but ther I'm lost. What is going on?

Thaks for any hint!

Laurent Bloch
  • 55
  • 1
  • 3
  • 2
    Don't put the `pub mod` stuff in your `fasta_multiple_cmp.rs` and `build_sequences_matrix.rs`. Also I'm not sure about this, but you might have to move the `pub mod fasta_multiple_cmp;` from `mod.rs` to `main.rs`. – Aplet123 Nov 04 '21 at 18:05
  • Thanks a lot! Now it is built. – Laurent Bloch Nov 04 '21 at 18:34
  • Does this answer your question? [Rust modules confusion when there is main.rs and lib.rs](https://stackoverflow.com/questions/57756927/rust-modules-confusion-when-there-is-main-rs-and-lib-rs) – BallpointBen Nov 04 '21 at 21:24

1 Answers1

6

Your original code wasn't working because Rust's use is looking for a crate to import from, not just a file in the same directory.

If you want to separate logic into other files, you will need to break apart your project into both a binary and into a library (aka - a crate that your binary can use for imports).

This can be done in your Cargo.toml as:

[package]
edition = "2018"
name = "my_project"
version = "1.2.3"

... your other settings ...

[[bin]]
edition = "2018"
name = "whatever_name_for_binary"
path = "src/main.rs"

This means that your binary will be compiled into a file called "whatever_name_for_binary" in your target folder. It also means your non-binary files act as a library, and can be imported by your binary by using use my_project::some_module;

Because your project will now contain both a library and binary, you will need to specify when you want to run/compile the binary.

You do this by running: cargo run --bin whatever_name_for_binary

For more information, see the Rust Book's Chapter on Modules.

anw
  • 370
  • 1
  • 5