6

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!

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. Commented Nov 4, 2021 at 18:05
  • Thanks a lot! Now it is built. Commented Nov 4, 2021 at 18:34
  • Does this answer your question? Rust modules confusion when there is main.rs and lib.rs Commented Nov 4, 2021 at 21:24

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.