Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell Cargo to build files other than main.rs?

Tags:

Here is my directory structure:

lowks@lowkster ~/src/rustlang/gettingrusty $ tree . . ├── Cargo.lock ├── Cargo.toml ├── foo.txt ├── src │   ├── boolean_example.rs │   ├── function_goodbye_world.rs │   ├── listdir.rs │   ├── looping.rs │   ├── main.rs │   ├── pattern_match.rs │   └── write_to_file.rs └── target     ├── build     ├── deps     ├── examples     ├── gettingrusty     └── native  6 directories, 11 files 

When I run 'cargo build', it seems to only build main.rs. How should I change Cargo.toml to build the rest of the files too?

like image 864
Muhammad Lukman Low Avatar asked Dec 23 '14 03:12

Muhammad Lukman Low


People also ask

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.

Where does cargo build output go?

Cargo stores the output of a build into the "target" directory. By default, this is the directory named target in the root of your workspace. To change the location, you can set the CARGO_TARGET_DIR environment variable, the build. target-dir config value, or the --target-dir command-line flag.

Does Rust need a main file?

By default, rustc produces a binary crate, not a library one, which needs a main() .

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.


2 Answers

Put other.rs file into bin subfolder of src folder (./src/bin/other.rs). And run cargo build --bin other or cargo run --bin other

like image 155
Andriy Viyatyk Avatar answered Sep 20 '22 09:09

Andriy Viyatyk


The Rust compiler compiles all the files at the same time to build a crate, which is either an executable or a library. To add files to your crate, add mod items to your crate root (here, main.rs) or to other modules:

mod boolean_example; mod function_goodbye_world; mod listdir; mod looping; mod pattern_match; mod write_to_file; 

To access items defined in another module from your crate root, you must qualify that item with the module name. For example, if you have a function named foo in module looping, you must refer to it as looping::foo.

You can also add use statements to import names in the module's scope. For example, if you add use looping::foo;, then you can just use foo to refer to looping::foo.

For more information, see Separating Modules into Different Files in The Rust Programming Language.

like image 25
Francis Gagné Avatar answered Sep 18 '22 09:09

Francis Gagné