Linker search paths on Mac OS X

I started working on a couple of Rust projects today and I had trouble on my Mac linking against the Snappy C library. This probably comes up a lot for beginners so I wanted to show my solution and see if there is a better way to solve it. I'm using a homebrew installed version of Snappy. I read Cargo's docs on build scripts.

Then, I decided to do this:

export DYLD_FALLBACK_LIBRARY_PATH=/usr/local/lib

and then I implemented a build.rs file like so:

fn main() {
    // if we're on Mac OS X we'll kindly add DYLD_FALLBACK_LIBRARY_PATH to rustc's
    // linker search path
    if let Some(dyld_fallback_path) = option_env!("DYLD_FALLBACK_LIBRARY_PATH") {
        println!("cargo:rustc-link-search=native={}", dyld_fallback_path)
    }
}

This seemed fairly sane to me, but I curious if there is a better way. Feedback welcome.

nice! Maybe splitting the string on ':' would not be a bad idea in case the user has more than one path listed in the environment variable.

fn main() {
    // if we're on Mac OS X we'll kindly add DYLD_FALLBACK_LIBRARY_PATH to rustc's
    // linker search path
    if let Some(dyld_fallback_paths) = option_env!("DYLD_FALLBACK_LIBRARY_PATH") {
        for path in dyld_fallback_paths.split(':') {
            println!("cargo:rustc-link-search=native={}", path)
        }
    }
}

Homebrew works with pkg-config, so Rust's pkg_config crate should set everything for you.

OS X is sensitive about link paths, and too many paths can break things, e.g. if you link with Cocoa framework having non-Apple libjpeg anywhere in the path breaks the build.

1 Like