Linking to a custom shared library

#1

I’m currently writing some bindings around some C++ library. My project contains a C wrapper on top of this C++ library which I build via a build.rs script using the cc crate.
The tricky bit is that this C++ library is usually a shared library and not in a system path (it could be in a custom user directory or in some conda environment).

In my build.rs script I can find the shared library and provide the appropriate -L /path/to/mylib and -lmylib flags to the C compiler. I also use the following to let the linker now about the shared library.

println!("cargo:rustc-link-lib=mylib")
println!("cargo:rustc-link-search=native=/path/to/mylib")

However I would also like the linker to set some rflags to /path/to/mylib so that the resulting binary can be run without needing some LD_LIBRARY_PATH override.
This can be done by setting RUSTFLAGS="-C link-args=-Wl,-rpath,/path/to/mylib" but in this case the path is found in build.rs and from this build script I don’t see how to pass this information to the linker. There doesn’t seem to be a way to pass flags other than -l or -L to the linker from what I understand.

Any thoughts on how this kind of thing could be done ?

Some alternative that I can think of is to have a small setup script (maybe in python) that would search for the library and create a .cargo/config file with the appropriate rustflags. If I do so I’m not sure if I can setup my crate so that the setup script will be called when installing it.

Just in case it matters, the library that I’m linking to is libtorch/PyTorch, my current bindings can be found in the tch-rs repo and here is my build.rs script.

#2

Cargo crates aren’t allowed to mess wth linker flags. In a typical scenario of using a third party library, the library is expected to have the correct path embedded already.

If it’s a custom library, it’s usually linked statically.

The custom-built and dynamic case doesn’t have a nice solution in Cargo.

If you don’t use a known system path, then the actual path may depend on how the final software package is structured, and Cargo doesn’t concern itself with packaging. It doesn’t even have any post-build actions.