Can my rust program print the opt-level with which it was compiled?

I'd like one of my binaries to print out the opt-level and perhaps other options with which it was compiled.

Is that possible?

I would think if it were possible, it would be done with cfg!() but the documentation seems pretty sparse:

Cargo defines the OPT_LEVEL environment variable (and a bunch more) for build scripts.

There's no cfg for that. People sometimes use cfg(debug_assertions) as a proxy for unoptimized or debug builds, but this setting can also be manually enabled in optimized release profiles too.

Aha, so option_env in std - Rust ... Thanks!

1 Like

Well... I thought this would work, but it just prints None... (running with cargo run)

  let optlev: Option<&'static str> = option_env!("OPT_LEVEL");
  println!("opt-level: {optlev:?}");

Oh I see. This only works for build scripts ( So I should probably follow the example here, and have emit a rust file that I then include in my main program:

Final solution:

//! build script for bex.
//! This generates a small rust file that lets bex
//! report what options were used for compilation.
use std::env;
use std::fs;
use std::path::Path;

fn main() {
    let out_dir = env::var_os("OUT_DIR").unwrap();
    let opt_level = env::var_os("OPT_LEVEL").unwrap();
    let bex_version = env!("CARGO_PKG_VERSION");
    let dest_path = Path::new(&out_dir).join("");
        const BEX_VERSION : &str = {bex_version:?};
        const BEX_OPT_LEVEL : &str = {opt_level:?};

the program

include!(concat!(env!("OUT_DIR"), "/"));

pub fn main() {
  println!("bex {BEX_VERSION} opt-level: {BEX_OPT_LEVEL}");
  // ...

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.