Conditional compilation: cargo vs build.rs

Hi,
I have a string path I would like changed based on a compile option.
After reading the obligatory documentation, there is still an half issue.

the module:

pub(crate) mod Paths_alts {

        #[cfg(feature = "localstr")]
        pub(crate) const PATH: &str = "/this/path";

        #[cfg(not(feature = "localstr"))]
        pub(crate) const PATH: &str = "/this/other/path";
}

the cargo:

...
[features]
localstr = []

My IDE (vscode) only highlights the "/this/other/path" for the PATH const. The other one is shaded.
Compilation selects the wrong str.

Instead, putting:
println!("cargo:rustc-cfg=str_path=\"localstr\""); in the build.rs, removing the features section in Cargo
and changing the code to

pub(crate) mod Paths_alts {

        #[cfg(str_path = "localstr")]
        pub(crate) const PATH: &str = "/this/path";

        #[cfg(not(str_path = "localstr"))]
        pub(crate) const PATH: &str = "/this/other/path";
}

Shows the correct behavior in the IDE and show "/this/path"

So, what did I do wrong only using features in Cargo ? Is there something else to add ?

thanks

You need to specify the default feature to include localstr:

[features]
default = ["localstr"]
localstr = []

https://doc.rust-lang.org/cargo/reference/features.html#the-default-feature

Or add it to rust-analyzer.cargo.features in your RA config if you only need it when using RA.

2 Likes

Ok missed that part.

Thank you!

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.