Version information of an executing binary

Is there a way to retrieve the version information of an executing rust binary? For example let's say we have the Cargo package information as below?

[package]
name = "exe1"
version = "0.1.0"
authors = ["Foo Bar <foo@foo.com>"]

Is there a way to retrieve the version information - 0.1.0 - encoded in Cargo.toml from main.rs?

1 Like

Cargo sets the CARGO_PKG_VERSION environment variable when it invokes rustc. You can use this to define a const in your executable to show it to the user. In libraries this is also useful.

pub const VERSION: &'static str = env!("CARGO_PKG_VERSION");

Please note that this line of code will yield an error if the environment variable isn't defined, for example if you execute rustc directly without cargo.

5 Likes

marvellous! Works like a charm!! :smile:

1 Like

Very helpful question and answer. Thanks. I had to add it immediately via the getopts crate to one of my example programs:

https://github.com/wahn/Rust_Examples/commit/97511fc3bcf7fd60cf69dc8638d34eca1764c33d