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

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.

主站蜘蛛池模板: 蒙城县| 兴仁县| 河曲县| 紫金县| 水城县| 威宁| 浑源县| 错那县| 简阳市| 肃南| 广宗县| 涟水县| 仪征市| 永丰县| 乐安县| 龙岩市| 天气| 荆州市| 渭源县| 中西区| 宝应县| 新巴尔虎左旗| 炎陵县| 万荣县| 乡城县| 济源市| 泌阳县| 衡南县| 开阳县| 商洛市| 米脂县| 蒙阴县| 陆川县| 和平县| 景德镇市| 丰镇市| 建瓯市| 宣汉县| 和静县| 章丘市| 冀州市|