Can't detect the crt-static setting in rust code

When I add the following build.rs file to my project:

fn main() {
    #[cfg(target_feature = "crt-static")]
    panic!("Detected crt-static mode");
}

...and build with RUSTFLAGS='-C target-feature=+crt-static -C relocation-model=static' cargo run --release --target x86_64-unknown-linux-gnu.

The build succeeds and the target_feature is not found. I don't understand if this is an intended part of the design?

This is using rust 1.70

Here's a the full example: GitHub - ctsa/detect_crt_static

Why do you think crt-static should affect anything? It's not in the list of supported target features.

If using a build script then see Environment Variables - The Cargo Book

I believe you'll want to parse CARGO_CFG_TARGET_FEATURE.

1 Like

You could also do

#[cfg(target_feature = "crt-static")]
compile_error!("Detected crt-static mode");

in your lib.rs.

Good question, it is listed in the documentation here:

https://doc.rust-lang.org/reference/conditional-compilation.html#target_feature

Are these docs out of date?

Thanks. For my motivating use case I'd like it in the build.rs to select which library I link.

Ok, I see it there!

Is there a criteria for when I should expect to see it in the CARGO_CFG_TARGET_FEATURE variable vs. having the above target_feature setting work? Do both need to be checked?

Basically CARGO_CFG_TARGET_FEATURE is only used in build scripts (aka build.rs). This is compiled and run on the host system, separately from your library or binary.

So the environment variable is necessary to get features for the target system rather than the host.

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.