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:
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!
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 (build.rs
)... So I should probably follow the example here, and have build.rs
emit a rust file that I then include in my main program:
https://doc.rust-lang.org/cargo/reference/build-script-examples.html
Final solution:
build.rs
//! 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("bex-build-info.rs");
fs::write(
&dest_path,
format!("
const BEX_VERSION : &str = {bex_version:?};
const BEX_OPT_LEVEL : &str = {opt_level:?};
")
).unwrap();
println!("cargo:rerun-if-changed=build.rs");
}
the program
include!(concat!(env!("OUT_DIR"), "/bex-build-info.rs"));
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.