Embed version number in the binary compiled by Rust

version CARGO_PKG_VERSION env! static const

There are a number of environment variables available during the build of a binary. One of them is the CARGO_PKG_VERSION variable that contains the version number as written in the Cargo.toml file.

Using the env! macro we can extract the value during the build phase of the compilation and we can include it on our code either as a constant using the const keyword or we can make it a regular variable either explicitely making it a static variable or letting Rust figure out the type.

The difference will be the location where the value is stored.

The code

examples/embed-version-number/src/main.rs

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

fn main() {
    let explicit_type_version: &'static str = env!("CARGO_PKG_VERSION");
    let implicit_type_version = env!("CARGO_PKG_VERSION");
    println!("Constant version {VERSION}");
    println!("Explicit version {explicit_type_version}");
    println!("Implicit version {implicit_type_version}");
}

Cargo.toml with the version number

examples/embed-version-number/Cargo.toml

[package]
name = "embed-version-number"
version = "1.2.3"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

Note

I'd go with the const.

If you only need to have a --version flag you can tell Clap to create a --version flag.

Related Pages

Clap - show version number of the command line application in Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo