Cargo 教程
Cargo 是什么
Cargo 是 Rust 的构建系统和包管理器。
Rust 开发者常用 Cargo 来管理 Rust 工程和获取工程所依赖的库。在上个教程中我们曾使用 cargo new greeting 命令创建了一个名为 greeting 的工程,Cargo 新建了一个名为 greeting 的文件夹并在里面部署了一个 Rust 工程最典型的文件结构。这个 greeting 文件夹就是工程本身。
Cargo 功能
Cargo 除了创建工程以外还具备构建(build)工程、运行(run)工程等一系列功能,构建和运行分别对应以下命令:
cargo build cargo run
Cargo 还具有获取包、打包、高级构建等功能,详细使用方法参见 Cargo 命令。
在 VSCode 中配置 Rust 工程
Cargo 是一个不错的构建工具,如果使 VSCode 与它相配合那么 VSCode 将会是一个十分便捷的开发环境。
在上一章中我们建立了 greeting 工程,现在我们用 VSCode 打开 greeting 文件夹(注意不是 runoob-greeting)。
打开 greeting 之后,在里面新建一个新的文件夹 .vscode (注意 vscode 前面的点,如果有这个文件夹就不需要新建了)。在新建的 .vscode 文件夹里新建两个文件 tasks.json 和 launch.json,文件内容如下:
tasks.json 文件 { "version": "2.0.0", "tasks": [ { "label": "build", "type": "shell", "command":"cargo", "args": ["build"] } ] }
launch.json 文件(适用在 Windows 系统上) { "version": "0.2.0", "configurations": [ { "name": "(Windows) 启动", "preLaunchTask": "build", "type": "cppvsdbg", "request": "launch", "program": "${workspaceFolder}/target/debug/${workspaceFolderBasename}.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false }, { "name": "(gdb) 启动", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/target/debug/${workspaceFolderBasename}.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "miDebuggerPath": "这里填GDB所在的目录", "setupCommands": [ { "description": "为 gdb 启用整齐打印", "text": "-enable-pretty-printing", "ignoreFailures": true } ] } ] }
launch.json 文件(适用在 Linux 系统上) { "version": "0.2.0", "configurations": [ { "name": "Debug", "type": "gdb", "preLaunchTask": "build", "request": "launch", "target": "${workspaceFolder}/target/debug/${workspaceFolderBasename}", "cwd": "${workspaceFolder}" } ] }
launch.json 文件(适用在 Mac OS 系统上) { "version": "0.2.0", "configurations": [ { "name": "Debug", "type": "gdb", "preLaunchTask": "build", "request": "launch", "target": "${workspaceFolder}/target/debug/${workspaceFolderBasename}", "cwd": "${workspaceFolder}" } ] }
然后点击 VSCode 左栏的 “运行”。
如果你使用的是 MSVC 选择 “(Windows) 启动”。
如果使用的是 MinGW 且安装了 GDB 选择"(gdb)启动",gdb 启动前请注意填写 launch.json 中的 “miDebuggerPath”。
![[Pasted image 20230606184946.png]]
程序就会开始调试运行了。运行输出将出现在"调试控制台"中:
![[Pasted image 20230606185006.png]]
在 VSCode 中调试 Rust
调试程序的方法与其它环境相似,只需要在行号的左侧点击红点就可以设置断点,在运行中遇到断点会暂停,以供开发者监视实时变量的值。
![[Pasted image 20230606185146.png]]
**注意:这里需要使用debug去运行程序才会进入到断点中,直接运行会顺次执行并返回执行时间。**如下图![[Pasted image 20230606185300.png]]
扩充:
cargo是Rust语言的包管理器,它可以帮助开发者获取、打包和构建Rust项目。下面是cargo的一些常用功能介绍及实例。
获取包
使用cargo可以方便地获取Rust语言的各种包,只需要在终端中输入以下命令即可:
cargo install package_name
例如,获取Rust语言的标准库:
cargo install std
打包
使用cargo可以将Rust项目打包成可执行文件或库文件,只需要在项目根目录下输入以下命令即可:
cargo build
例如,将一个名为"hello"的Rust项目打包成可执行文件:
cd hello cargo build
高级构建功能
cargo还提供了一些高级构建功能,例如:
优化构建速度:使用cargo的–release选项可以优化构建速度,生成的可执行文件也会更快。
cargo build --release
构建指定目标平台:使用cargo的–target选项可以构建指定目标平台的可执行文件或库文件。
cargo build --target x86_64-unknown-linux-gnu
构建指定特性:使用cargo的–features选项可以构建指定特性的可执行文件或库文件。
cargo build --features "feature1 feature2"
以上是cargo的一些常用功能介绍及实例,希望对你有所帮助。
再补充几个 cargo 的重要子命令:
cargo clippy: 类似eslint,lint工具检查代码可以优化的地方
cargo fmt: 类似go fmt,代码格式化
cargo tree: 查看第三方库的版本和依赖关系
cargo bench: 运行benchmark(基准测试,性能测试)
cargo udeps(第三方): 检查项目中未使用的依赖
另外 cargo build/run --release 使用 release 编译会比默认的 debug 编译性能提升 10 倍以上,但是 release 缺点是编译速度较慢,而且不会显示 panic backtrace 的具体行号
cargo build 帮助手册
需要执行命令cargo help build
英文原版
CARGO-BUILD(1) NAME cargo-build — Compile the current package SYNOPSIS cargo build [options] DESCRIPTION Compile local packages and all of their dependencies. OPTIONS Package Selection By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected. The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace), and a non-virtual workspace will include only the root crate itself. -p spec…, --package spec… Build only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like *, ? and []. However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. --workspace Build all members in the workspace. --all Deprecated alias for --workspace. --exclude SPEC… Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like *, ? and []. However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Target Selection When no target selection options are given, cargo build will build all binary and library targets of the selected packages. Binaries are skipped if they have required-features that are missing. Binary targets are automatically built if there is an integration test or benchmark being selected to build. This allows an integration test to execute the binary to exercise and test its behavior. The CARGO_BIN_EXE_<name> environment variable <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates> is set when the integration test is built so that it can use the env macro <https://doc.rust-lang.org/std/macro.env.html> to locate the executable. Passing target selection flags will build only the specified targets. Note that --bin, --example, --test and --bench flags also support common Unix glob patterns like *, ? and []. However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each glob pattern. --lib Build the package’s library. --bin name… Build the specified binary. This flag may be specified multiple times and supports common Unix glob patterns. --bins Build all binary targets. --example name… Build the specified example. This flag may be specified multiple times and supports common Unix glob patterns. --examples Build all example targets. --test name… Build the specified integration test. This flag may be specified multiple times and supports common Unix glob patterns. --tests Build all targets in test mode that have the test = true manifest flag set. By default this includes the library and binaries built as unittests, and integration tests. Be aware that this will also build any required dependencies, so the lib target may be built twice (once as a unittest, and once as a dependency for binaries, integration tests, etc.). Targets may be enabled or disabled by setting the test flag in the manifest settings for the target. --bench name… Build the specified benchmark. This flag may be specified multiple times and supports common Unix glob patterns. --benches Build all targets in benchmark mode that have the bench = true manifest flag set. By default this includes the library and binaries built as benchmarks, and bench targets. Be aware that this will also build any required dependencies, so the lib target may be built twice (once as a benchmark, and once as a dependency for binaries, benchmarks, etc.). Targets may be enabled or disabled by setting the bench flag in the manifest settings for the target. --all-targets Build all targets. This is equivalent to specifying --lib --bins --tests --benches --examples. Feature Selection The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package. See the features documentation <https://doc.rust-lang.org/cargo/reference/features.html#command-line-feature-options> for more details. -F features, --features features Space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name syntax. This flag may be specified multiple times, which enables all specified features. --all-features Activate all available features of all selected packages. --no-default-features Do not activate the default feature of the selected packages. Compilation Options --target triple Build for the given architecture. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi>. Run rustc --print target-list for a list of supported targets. This flag may be specified multiple times. This may also be specified with the build.target config value <https://doc.rust-lang.org/cargo/reference/config.html>. Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache <https://doc.rust-lang.org/cargo/guide/build-cache.html> documentation for more details. -r, --release Build optimized artifacts with the release profile. See also the --profile option for choosing a specific profile by name. --profile name Build with the given profile. See the the reference <https://doc.rust-lang.org/cargo/reference/profiles.html> for more details on profiles. --ignore-rust-version Build the target even if the selected Rust compiler is older than the required Rust version as configured in the project’s rust-version field. --timings=fmts Output information how long each compilation takes, and track concurrency information over time. Accepts an optional comma-separated list of output formats; --timings without an argument will default to --timings=html. Specifying an output format (rather than the default) is unstable and requires -Zunstable-options. Valid output formats: o html (unstable, requires -Zunstable-options): Write a human-readable file cargo-timing.html to the target/cargo-timings directory with a report of the compilation. Also write a report to the same directory with a timestamp in the filename if you want to look at older runs. HTML output is suitable for human consumption only, and does not provide machine-readable timing data. o json (unstable, requires -Zunstable-options): Emit machine-readable JSON information about timing information. Output Options --target-dir directory Directory for all generated artifacts and intermediate files. May also be specified with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value <https://doc.rust-lang.org/cargo/reference/config.html>. Defaults to target in the root of the workspace. --out-dir directory Copy final artifacts to this directory. This option is unstable and available only on the nightly channel <https://doc.rust-lang.org/book/appendix-07-nightly-rust.html> and requires the -Z unstable-options flag to enable. See <https://github.com/rust-lang/cargo/issues/6790> for more information. Display Options -v, --verbose Use verbose output. May be specified twice for “very verbose” output which includes extra output such as dependency warnings and build script output. May also be specified with the term.verbose config value <https://doc.rust-lang.org/cargo/reference/config.html>. -q, --quiet Do not print cargo log messages. May also be specified with the term.quiet config value <https://doc.rust-lang.org/cargo/reference/config.html>. --color when Control when colored output is used. Valid values: o auto (default): Automatically detect if color support is available on the terminal. o always: Always display colors. o never: Never display colors. May also be specified with the term.color config value <https://doc.rust-lang.org/cargo/reference/config.html>. --message-format fmt The output format for diagnostic messages. Can be specified multiple times and consists of comma-separated values. Valid values: o human (default): Display in a human-readable text format. Conflicts with short and json. o short: Emit shorter, human-readable text messages. Conflicts with human and json. o json: Emit JSON messages to stdout. See the reference <https://doc.rust-lang.org/cargo/reference/external-tools.html#json-messages> for more details. Conflicts with human and short. o json-diagnostic-short: Ensure the rendered field of JSON messages contains the “short” rendering from rustc. Cannot be used with human or short. o json-diagnostic-rendered-ansi: Ensure the rendered field of JSON messages contains embedded ANSI color codes for respecting rustc’s default color scheme. Cannot be used with human or short. o json-render-diagnostics: Instruct Cargo to not include rustc diagnostics in JSON messages printed, but instead Cargo itself should render the JSON diagnostics coming from rustc. Cargo’s own JSON diagnostics and others coming from rustc are still emitted. Cannot be used with human or short. --build-plan Outputs a series of JSON messages to stdout that indicate the commands to run the build. This option is unstable and available only on the nightly channel <https://doc.rust-lang.org/book/appendix-07-nightly-rust.html> and requires the -Z unstable-options flag to enable. See <https://github.com/rust-lang/cargo/issues/5579> for more information. Manifest Options --manifest-path path Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory. --frozen, --locked Either of these flags requires that the Cargo.lock file is up-to-date. If the lock file is missing, or it needs to be updated, Cargo will exit with an error. The --frozen flag also prevents Cargo from attempting to access the network to determine if it is out-of-date. These may be used in environments where you want to assert that the Cargo.lock file is up-to-date (such as a CI build) or want to avoid network access. --offline Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible. Beware that this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See the cargo-fetch(1) command to download dependencies before going offline. May also be specified with the net.offline config value <https://doc.rust-lang.org/cargo/reference/config.html>. Common Options +toolchain If Cargo has been installed with rustup, and the first argument to cargo begins with +, it will be interpreted as a rustup toolchain name (such as +stable or +nightly). See the rustup documentation <https://rust-lang.github.io/rustup/overrides.html> for more information about how toolchain overrides work. --config KEY=VALUE or PATH Overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE, or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section <https://doc.rust-lang.org/cargo/reference/config.html#command-line-overrides> for more information. -C PATH Changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest (Cargo.toml), as well as the directories searched for discovering .cargo/config.toml, for example. This option is only available on the nightly channel <https://doc.rust-lang.org/book/appendix-07-nightly-rust.html> and requires the -Z unstable-options flag to enable (see #10098 <https://github.com/rust-lang/cargo/issues/10098>). -h, --help Prints help information. -Z flag Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. Miscellaneous Options -j N, --jobs N Number of parallel jobs to run. May also be specified with the build.jobs config value <https://doc.rust-lang.org/cargo/reference/config.html>. Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus provided value. Should not be 0. --keep-going Build as many crates in the dependency graph as possible, rather than aborting the build on the first one that fails to build. Unstable, requires -Zunstable-options. --future-incompat-report Displays a future-incompat report for any future-incompatible warnings produced during execution of this command See cargo-report(1) ENVIRONMENT See the reference <https://doc.rust-lang.org/cargo/reference/environment-variables.html> for details on environment variables that Cargo reads. EXIT STATUS o 0: Cargo succeeded. o 101: Cargo failed to complete. EXAMPLES 1. Build the local package and all of its dependencies: cargo build 2. Build with optimizations: cargo build --release SEE ALSO cargo(1), cargo-rustc(1)
中文版本(部分)(剩下的没翻完)
翻译如下:
翻译如下: CARGO-BUILD(1) 名称 cargo-build - 编译当前包 概要 cargo build [选项] 描述 编译本地包及其所有依赖项。 选项 包选择 默认情况下,当没有给出包选择选项时,所选的包取决于所选的清单文件(如果未给出--manifest-path,则基于当前工作目录)。如果清单是工作区的根,则选择工作区的默认成员,否则仅选择由清单定义的包。 工作区的默认成员可以在根清单中显式设置为workspace.default-members键。如果未设置此项,则虚拟工作区将包括所有工作区成员(等效于传递--workspace),而非虚拟工作区将仅包括根箱本身。 -p spec…,--package spec… 仅构建指定的包。有关SPEC格式,请参见cargo-pkgid(1)。此标志可以多次指定,并支持常见的Unix glob模式,例如*,?和[]。但是,为了避免您的shell在Cargo处理它们之前意外扩展glob模式,您必须在每个模式周围使用单引号或双引号。 --workspace 构建工作区中的所有成员。 --all --workspace的弃用别名。 --exclude SPEC… 排除指定的包。必须与--workspace标志一起使用。此标志可以多次指定,并支持常见的Unix glob模式,例如*,?和[]。但是,为了避免您的shell在Cargo处理它们之前意外扩展glob模式,您必须在每个模式周围使用单引号或双引号。 目标选择 当没有给出目标选择选项时,cargo build将构建所选包的所有二进制和库目标。如果二进制文件缺少所需的功能,则会跳过它们。 如果选择构建集成测试或基准测试,则会自动构建二进制目标。这允许集成测试执行二进制文件以测试其行为。当构建集成测试时,设置CARGO_BIN_EXE_<name>环境变量<https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates>,以便它可以使用env宏<https://doc.rust-lang.org/std/macro.env.html>来定位可执行文件。 传递目标选择标志将仅构建指定的目标。 请注意,--bin、--example、--test和--bench标志也支持常见的Unix glob模式,例如*,?和[]。但是,为了避免您的
问题
还是没找到从命令行指定生成之后的程序名称的方式,--bin、--name都不行。
文档中修改的方式倒是找到了。