如何使用 rustc-env 标志指定环境变量? [英] How to specify an environment variable using the rustc-env flag?

查看:36
本文介绍了如何使用 rustc-env 标志指定环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置 rustc-env=VAR=VALUE 以便我可以在我的代码中使用 env::var("VAR") 访问它.但是,我不清楚在哪里指定它.我可以在 Makefile 中设置环境变量 VAR 吗?

I want to set rustc-env=VAR=VALUE so that I could access it using env::var("VAR") in my code. However, I'm not clear on where to specify it. Can I set the environment variable VAR in the Makefile?

推荐答案

TL;DR

build.rs

fn main() {
    println!("cargo:rustc-env=VAR=VALUE");
}

src/main.rs

fn main() {
    let var = env!("VAR");
}

<小时>

您链接的文档适用于 Cargo 构建脚本:


The documentation that you linked is for a Cargo build script:

build 命令指定的 Rust 文件(相对于包根目录)将在包中编译其他任何东西之前被编译和调用,允许你的 Rust 代码依赖于构建或生成的文物.默认情况下,Cargo 在包根目录中查找 "build.rs" 文件(即使您没有为 build 指定值).使用 build = "custom_build_name.rs" 指定自定义构建名称或 build = false 禁用构建脚本的自动检测.

The Rust file designated by the build command (relative to the package root) will be compiled and invoked before anything else is compiled in the package, allowing your Rust code to depend on the built or generated artifacts. By default Cargo looks up for "build.rs" file in a package root (even if you do not specify a value for build). Use build = "custom_build_name.rs" to specify a custom build name or build = false to disable automatic detection of the build script.

在同一页面上,有一个 描述 build.rs 输出的部分

On the same page, there's a section that describes outputs of build.rs

构建脚本打印到标准输出的所有行都写入文件 [...] 任何以 cargo: 开头的行都由 Cargo 直接解释.此行必须采用 cargo:key=value 形式,如下例所示:

All the lines printed to stdout by a build script are written to a file [...] Any line that starts with cargo: is interpreted directly by Cargo. This line must be of the form cargo:key=value, like the examples below:

cargo:rustc-env=FOO=bar

然后详细说明rustc-env:

rustc-env=VAR=VALUE 表示指定的环境变量将被添加到编译器运行的环境中.然后可以通过编译的 crate 中的 env! 宏检索该值.这对于在 crate 的代码中嵌入额外的元数据很有用,例如 Git HEAD 的哈希值或持续集成服务器的唯一标识符.

rustc-env=VAR=VALUE indicates that the specified environment variable will be added to the environment which the compiler is run within. The value can be then retrieved by the env! macro in the compiled crate. This is useful for embedding additional metadata in crate's code, such as the hash of Git HEAD or the unique identifier of a continuous integration server.

env! 是一个宏.

使用 env::var("VAR")

没有.env::var 用于读取程序运行时设置的环境变量,而不是编译时设置的.

No. env::var is for reading environment variables set when the program runs, not when the program is compiled.

另见:

这篇关于如何使用 rustc-env 标志指定环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆