Compile-time configuration of installation directories

The autotools are providing a suite of utilities allowing the developer to configure the source code during compilation specifically to ease packaging.

One of the capabilities is the definition of several installation directory variables set during compilation and which avoids making assumptions on where the application is to be installed.

For example:

Variable Default
prefix /usr/local
datarootdir ${prefix}/share
sysconfdir ${prefix}/etc
localstatedir ${prefix}/var
...

How to mimic this behavior in Rust at compile time? Is there any existing standard or best practices for such need?

I'd like to make use of system paths but without having them fully hard-coded and allowing the packager to customize part of it.

You can use the env! macro to get at system configuration values, which is how Rust usually gets integrated with stuff like autoconf and pkg-config.

notriddle$ cat test.rs
fn main() {
    println!("{}", env!("testop"));
}
notriddle$ testop="Hello World!" rustc test.rs
notriddle$ ./test
Hello World!

Cargo's build.rs lets you set up these env vars automatically, if you want to do system feature detection.

But that's not what the Rust compiler does, and it's not what I recommend, either. Instead, you can use the current_exe function to detect where the sysroot actually is. That way, you can distribute your application as a portable package, that can optionally be extracted into /usr/local/ or into someone's home folder without having to recompile it.

build.rs sounds like what approaching the most so far since configuration can be about anything. current_exe only fixes part of the problem. What about location of system level configuration files or local state or anything else system dependent.

Yeah, that sort of thing probably should be configured using build.rs and the env! macro, or runtime environment variables, or both (with the runtime env variables having priority).

I brought up current_exe because, as useful as build.rs is, it's more convenient to install if your application is designed to be relocatable.

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.