Rust:专属的cargo工具介绍

简介: 程序就会开始调试运行了。运行输出将出现在"调试控制台"中:

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都不行。

文档中修改的方式倒是找到了。

相关实践学习
阿里云图数据库GDB入门与应用
图数据库(Graph Database,简称GDB)是一种支持Property Graph图模型、用于处理高度连接数据查询与存储的实时、可靠的在线数据库服务。它支持Apache TinkerPop Gremlin查询语言,可以帮您快速构建基于高度连接的数据集的应用程序。GDB非常适合社交网络、欺诈检测、推荐引擎、实时图谱、网络/IT运营这类高度互连数据集的场景。 GDB由阿里云自主研发,具备如下优势: 标准图查询语言:支持属性图,高度兼容Gremlin图查询语言。 高度优化的自研引擎:高度优化的自研图计算层和存储层,云盘多副本保障数据超高可靠,支持ACID事务。 服务高可用:支持高可用实例,节点故障迅速转移,保障业务连续性。 易运维:提供备份恢复、自动升级、监控告警、故障切换等丰富的运维功能,大幅降低运维成本。 产品主页:https://www.aliyun.com/product/gdb
目录
相关文章
|
6月前
|
Rust 数据可视化 安全
Rust性能分析工具概览:perf、flamegraph 与其他
Rust作为一种高性能、内存安全的编程语言,在构建大型系统和微服务时备受青睐。然而,优化Rust程序的性能需要有效的工具。本文将对Rust中常用的性能分析工具进行介绍,包括perf、flamegraph等,并探讨它们如何帮助开发者定位和解决性能瓶颈。
|
2月前
|
Rust 编译器 测试技术
30天拿下Rust之深入Cargo
30天拿下Rust之深入Cargo
32 0
|
3月前
|
Rust 编译器 开发者
Cargo:Rust的神秘助手,它将如何改变包管理游戏规则?
【8月更文挑战第31天】Rust的包管理器Cargo简化了依赖管理和构建过程,与编译器无缝集成,提供从依赖下载到编译构建的全套解决方案。通过`cargo new`创建项目后,编辑`Cargo.toml`文件即可轻松管理依赖。Cargo还支持自动生成文档、运行测试及发布代码,并通过`crates.io`平台方便查找和分享Rust库,是Rust生态系统中的重要工具,有助于提升开发者生产力。
57 1
|
4月前
|
Rust 测试技术 编译器
Rust与C++的区别及使用问题之Rust项目中组织目录结构的问题如何解决
Rust与C++的区别及使用问题之Rust项目中组织目录结构的问题如何解决
|
5月前
|
Rust Shell 索引
使用阿里云镜像加速Rust与Cargo安装及更新
使用阿里云镜像加速Rust与Cargo安装及更新
1059 0
|
5月前
|
Rust Unix Windows
使用Cargo国内镜像提升Rust开发效率
使用Cargo国内镜像提升Rust开发效率
439 0
|
5月前
|
Rust
使用Cargo创建、编译与运行Rust项目
使用Cargo创建、编译与运行Rust项目
188 0
|
6月前
|
Rust 监控 安全
【专栏】`ripgrep`(rg)是Linux下快速、内存高效的文本搜索工具,用Rust编写,支持PCRE2正则表达式
【4月更文挑战第28天】`ripgrep`(rg)是Linux下快速、内存高效的文本搜索工具,用Rust编写,支持PCRE2正则表达式。相比`grep`,它在处理大文件和复杂模式时更具优势。安装`rg`可通过软件包管理器,如在Debian系系统中使用`sudo apt install ripgrep`。基本用法包括简单搜索、递归搜索、忽略大小写、显示行号等。高级功能包括固定字符串搜索、多文件匹配、并行搜索、排除选项和区域搜索。适用于日志分析、代码审查等场景,是提升工作效率的利器。
530 4
|
6月前
|
Rust 监控 网络协议
运用Rust编写高效的远程监控多台电脑屏幕工具
使用Rust编程语言开发远程监控多台电脑屏幕的工具,通过安装客户端实时传输屏幕截图至监控端。示例代码展示如何利用Rust的网络编程和图像处理库捕获、发送及接收屏幕截图。监控端接收到数据后可进行保存或上传等处理,实现高效可靠的远程监控解决方案。
205 2
|
6月前
|
Rust Java 编译器
学Rust不学Cargo,等于没学Rust:workspace详解
Rust 中的`Workspace`是一种组织多个 Rust crate(项目或库)的结构。使得它们可以协同工作、共享依赖关系,以及更方便地进行管理和构建。 如果你是Java开发者,workspace这个概念类似Java中的`maven`父工程。 子工程可以共享父工程中的很多配置项,如依赖,版本等配置。子工程可以`选择性的继承`父工程的配置。
129 2