Rust build tool cargo

environment

  • windows 10 64bit

foreword

We have installed the Rust development environment before. During this process, cargo is also installed, which can be checked by cargo --version

cargo is a built-in build tool and package manager in the Rust toolchain. It can help us build code, download, compile and manage dependency libraries. It is also currently the recommended Rust project management tool.

example

We enter powershell and use cargo to create a new project

 cargo new HelloWorld

After the command is successfully executed, the project is created. The project name and folder name are both HelloWorld . Enter the directory HelloWorld . The folder structure is like this

The source code part is placed in the src directory and the project configuration file Cargo.toml . At the same time, a new git warehouse is initialized and a default .gitignore file is provided.

Let’s take a look at the project configuration Cargo.toml , cargo uses the standard TOML configuration file format, TOML is the abbreviation of Tom's Obvious, Minimal Language

Among them, [] is the area label, such as package and dependencies in this project, under the package label, there are program name, version number and author information, because this project is very simple and does not depend on third-party libraries, so dependencies are empty

Next, use cargo to build and compile

 cd HelloWorld cargo build

After the end, the generated executable file is stored in target/debug/HelloWorld.exe , and the result can be obtained by executing it in powershell

When the project is built, the root directory will generate a file Cargo.lock

It is best not to manually edit this file, it will maintain itself and record the version numbers of all dependent libraries in the project.

In addition to directly executing the generated exe file, we can also run it through cargo , the command is cargo run

Let me explain here that after executing cargo build , cargo run will not compile again. This is because the source code has not been changed, so it is executed directly

If at this time, let’s modify main.rs , modify the output statement, and then execute cargo run

At this time, the output information is different, and the source code has also been recompiled.

Another very useful command is cargo check , which can quickly check that the current code can be compiled normally without executing it.

As you can see, the default cargo is built in debug mode, which contains a lot of debugging information. If you want to release it officially, you can keep up with the parameter --release

 cargo run --release

Correspondingly, the generated exe file is placed in the target/release directory

This article is transferred from https://xugaoxiang.com/2022/12/16/rust-cargo/
This site is only for collection, and the copyright belongs to the original author.