Passing symbol values to the Rust compiler during build

青春壹個敷衍的年華 提交于 2021-01-29 21:39:53

问题


In my Go builds, I usually include these lines:

buildInfo="`date -u '+%Y-%m-%dT%TZ'`|`git describe --always --long`|`git tag | tail -1`"
go build -ldflags "-X main.buildInfo=${buildInfo} -s -w" ./cmd/...

and then in main, I parse buildInfo into three separate values which can be displayed with the usage message. This allows me to see the compile timestamp, git hash, and semver number of the executable.

Is there any similar way to do this in the Rust compiler?


回答1:


You want to use a Build Script as described here: https://doc.rust-lang.org/cargo/reference/build-scripts.html

You need to write a build.rs Rust file located at the root of your crate, which will be compiled and run by cargo just before building the crate, in which you can output certain strings that will in turn be interpreted by Cargo to drive compilation.

For example, if you write a build script with these contents:

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

Then the source files in your project can use the BUILD_INFO variable like this:

let buildInfo = env!("BUILD_INFO");

In your case, the build script can for example determine the current timestamp, or invoke the git executable and parse its output.



来源:https://stackoverflow.com/questions/60549943/passing-symbol-values-to-the-rust-compiler-during-build

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!