简体   繁体   English

如何使用rustc-env标志指定环境变量?

[英]How to specify an environment variable using the rustc-env flag?

I want to set rustc-env=VAR=VALUE so that I could access it using env::var("VAR") in my code. 我想设置rustc-env=VAR=VALUE以便可以在代码中使用env::var("VAR")来访问它。 However, I'm not clear on where to specify it. 但是,我不清楚在哪里指定它。 Can I set the environment variable VAR in the Makefile? 我可以在Makefile中设置环境变量VAR吗?

TL;DR TL; DR

build.rs 构建器

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

src/main.rs src / main.rs

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

The documentation that you linked is for a Cargo build script : 您链接文档适用于Cargo 构建脚本

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. build命令指定的Rust文件(相对于软件包根目录)将在软件包中进行其他编译之前先进行编译和调用,从而使您的Rust代码依赖于所生成或生成的工件。 By default Cargo looks up for "build.rs" file in a package root (even if you do not specify a value for build ). 默认情况下,Cargo在软件包根目录中查找"build.rs"文件(即使您未为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 = "custom_build_name.rs"指定自定义的构建名称,或使用build = false禁用对构建脚本的自动检测。

On the same page, there's a section that describes outputs of build.rs 在同一页面上,有一节描述了build.rs的输出

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. daccess-ods.un.org daccess-ods.un.org由构建脚本打印到stdout的所有行都被写入文件。任何以cargo:开头的行都由Cargo直接解释。 This line must be of the form cargo:key=value , like the examples below: 该行的格式必须为cargo:key=value ,如下例所示:

 cargo:rustc-env=FOO=bar 

It then details rustc-env : 然后详细介绍rustc-env

rustc-env=VAR=VALUE indicates that the specified environment variable will be added to the environment which the compiler is run within. rustc-env=VAR=VALUE表示将指定的环境变量添加到运行编译器的环境中。 The value can be then retrieved by the env! 然后可以由env!检索该值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. 这对于在板条箱的代码中嵌入其他元数据很有用,例如Git HEAD的哈希或连续集成服务器的唯一标识符。

env! is a macro. 是一个宏。


access it using env::var("VAR") 使用env::var("VAR")访问它

No. env::var is for reading environment variables set when the program runs , not when the program is compiled . env::var用于读取程序运行时设置的环境变量,而不是编译程序时设置的环境变量。

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM