Compiling our project

The basic command to compile a Rust program is simple: cargo build.

We need to be in the directory containing Cargo.toml (or any subdirectory of that directory) in order to be able to do this, since that's how the cargo program knows which project to compile. However, we don't need to give it any other information, since everything it needs to know is in the metadata file. 

Here, we see the result of building the chapter02 source code:

The warnings are expected and do not prevent the compile from succeeding. If we look at those warnings carefully, we can see that Rust is a lot more helpful with its warnings than many programming languages, giving us hints for improving efficiency and such, rather than just talking about language syntax.

When we build the program, a Cargo.lock file and target directory are created.

Cargo.lock records the exact versions of dependencies that were used to build the project, which makes it much easier to produce repeatable results from different compilations of the same program. It's largely safe to ignore this file, as cargo will usually take care of anything that needs to be done with it.

The Rust community recommends that the Cargo.lock file should be added to your version control system (Git, for example) if your project is a program, but not if your project is a library. That's because a program's Cargo.lock file stores all of the versions that resulted in a successful compile of a complete program, where a library's only encompasses part of the picture, and so can lead to more confusion than help when distributed to others.

The target directory contains all of the build artifacts and intermediate files resulting from the compilation process, as well as the final program file. Storing the intermediate files allows future compiles to process only those files that need to be processed, and so speeds up the compilation process.

Our program itself is in the target/debug/foo file (or targetdebugfoo.exe on Windows) and we can navigate to it and run it manually if we want to. However, cargo provides a shortcut: cargo run.

We can use that command from any subdirectory of our project, and it will find and run our program for us.

Additionally, cargo run implies cargo build, meaning that if we've changed the source code since the last time we ran the program, cargo run will recompile the program before running it. That means we can just alternate between making changes to our code and executing it with cargo run to see it in action.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.74.25