官术网_书友最值得收藏!

  • Rust Quick Start Guide
  • Daniel Arbuckle
  • 444字
  • 2021-06-10 19:46:01

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 target\debug\foo.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.

主站蜘蛛池模板: 确山县| 临沭县| 江都市| 株洲市| 漠河县| 永顺县| 正宁县| 项城市| 宣汉县| 苗栗市| 汉川市| 佛冈县| 石阡县| 高密市| 保山市| 永宁县| 昌吉市| 宁国市| 延寿县| 龙泉市| 辽阳县| 塘沽区| 会东县| 广安市| 和田市| 大英县| 金华市| 云林县| 赤壁市| 邯郸县| 九寨沟县| 乌兰察布市| 大庆市| 兰州市| 饶河县| 桦南县| 长丰县| 咸丰县| 平潭县| 海林市| 肥东县|