Manging enviroment variables that were set before calling cargo

Let's say I have the command OPENSSL_STATIC=1 OPENSSL_LIB_DIR=<some-pkg-config-command> cargo b that builds a binary (link openssl statically). Can I just call cargo b and deal with environment files inside the build.rs?

I tried Build Scripts - The Cargo Book (not working or may be I am holding it wrong), and std::env::set_var inside build.rs (didn't work).

Ideally, I'd prefer not to use another script/tool to set environment variables, e.g., OPENSSL_LIB_DIR, which is fetched using pkg-config. before I call cargo b. I do have Justfile in my build pipeline though.

You can just put em in your .cargo/config.toml: Configuration - The Cargo Book

You can set environment variables that should be added to your build script invocations in the [env] section of your Cargo configuration file.

(previous answer beat me to the punch :slightly_smiling_face:)

This looks promising. Examples show static environment variables only. I guess I can't set this variable during build time? I need to call pkg-config to get include path of openssl and set an environment variable. The only place I know that is called at build-time is build.rs.

Another option is to streamline the pipeline using cargo-xtask.

There's two issues with build.rs:

  1. Your build.rs is run after dependencies are built.
  2. You can't tell cargo to rerun build.rs based on arbitrary logic.

So you'll need to do this outside of cargo. Looks like cargo-xtask would work.

1 Like

The openssl crate (technically, openssl-sys) will look in pkg-config automatically; are you sure you need to set this in the first place?

the former only sets envars when building your crate, not it's dependencies. the latter only affects that build script, not any processes cargo invokes after reading the output of that build script, such as rustc.