Use compile-time parameter inside program

I'd like to pass the compile time as a parameter into my embedded program. How can I achieve that?
I think about running the program with something like cargo run -- "2024-04-21T10:06:20Z" to set the internal clock of the target to this timestamp.
But can be any parameter, it's not (yet) so much about the time stamp parsing.

Thanks a lot!

You can use a build script for this.

Cargo.toml:

[build-dependencies]
chrono = { version = "0.4", default-features = false, features = ["now"] }

build.rs:

fn main() {
    println!("cargo::rustc-env=BUILD_TIME={}", chrono::Utc::now());
}

main.rs:

fn main() {
    println!("Application built on {}", env!("BUILD_TIME"));
}
2 Likes

Great, thank You very much!

Is there a alternative way via cargo command line? Because I might want by to choose a different timestamp than "now", or also choose not to set the time at all (by leaving out the argument). I wanted to avoid to change a source or config file for this.

Set the environment variable on the command line and use the same env! macro to statically include it into the executable.

Yes, this is where I stumble upon:
With
BUILD_TIME="2024-04-21T10:06:20Z";cargo run
I get
environment variable 'BUILD_TIME' not defined at compile time
I think I must say, that I'm totally new to rust, so I'm not sure how to set an environment variable.

Remove the semicolon or export the var.

$ BUILD_TIME="2024-04-21T10:06:20Z" cargo run
   Compiling build-time v0.1.0 (C:\Users\jay\Desktop\build-time)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.32s
     Running `target\debug\build-time.exe`
Application built on 2024-04-21T10:06:20Z
$ export BUILD_TIME="2024-04-21T10:06:20Z"
$ cargo run
   Compiling build-time v0.1.0 (C:\Users\jay\Desktop\build-time)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.19s
     Running `target\debug\build-time.exe`
Application built on 2024-04-21T10:06:20Z

You will need a build script anyway to rebuild when the environment variable changes (but you can remove the [build-dependencies].

build.rs:

fn main() {
    println!("cargo::rerun-if-env-changed=BUILD_TIME");
}
2 Likes

Ahh, that's it. I was so close...
BUILD_TIME="2024-04-21T10:06:20Z" cargo run

Cargo rebuilds also without that line in build.rs.

Thank You very much!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.