I try to pass a variable from a dependency to the actual project package.
As far as I understand the build script documentation cargo::metadata should be able to do that.
For testing I created a library project cargo new --lib libbaz and added the following lines to the build.rs
As far as I understand the documentation this way libbaz should pass the variable MY_VAR to foo where it can be read in the build script as DEP_BAZ_MY_VAR, but instead I get the error
[foo_project 0.1.0] thread 'main' panicked at build.rs:4:50:
[foo_project 0.1.0] called `Result::unwrap()` on an `Err` value: NotPresent
I tried with different setups and tried different naming convention for the DEP_ variable and printed the whole environment. No DEP_ variable is present.
either it's a typo, or you have misunderstood how the links key works.
the links key should be in the -sys crate that links against native libraries (libbaz in your example), not the dependent of the -sys crate (foo_project in your example).
Ah, thanks for the clarification. I indeed understood that wrong. Ok, in this toy example I don't have a native library anyways, so I probably could remove that.
How is it with the cargo::metadata forwarding? MY_VAR should still show up as DEP_BAZ_MY_VAR in the build script of foo, shouldn't it?
you should put it in the Cargo.toml manifest of libbaz.
cargo::metadata is specificaly designed for crates that link to native libraries, it is not passed to the build scripts of dependent crates if the crate doesn't have a links key. in other words, it is NOT intended as a method for rust libraries to pass arbitrary information to their dependents in general.
no it shouldn't, as the environment variable name is according to the links key, not the crate's package name.
for example, if the crate is named foo, but its manifest has links = bar, then a metadata my_var=xYz will turn into an environment variable DEP_BAR_MY_VAR=xYz for its dependents, not DEP_FOO_MY_VAR.
Thanks a lot for the detailed explanation. I got it to work.
I was also wondering about the naming convention of the DEP_* variable, but now it makes sense that is just the name one adds to the links keyword.