Static library linkage error
Recently I encountered a strange linkage error when building FFI library bindings with rust and cargo. I'm not sure if it's a bug but it's surely annoying. Here is a minimal working example of the problem.
Example Description
Let's say you have two static libraries: libfoo.a and libbar.a, where
the later depends on some symbols from the former.
You are writing two FFI binding crates, rust-foo-sys and rust-bar-sys for these
libraries. To do this, you print cargo:rustc-link-lib={kind}={libname} in
both crates' build scripts. In in the former crate you specify kind
to be static but in the later crate you don't specify
the kind and leave the choice to the compiler.
A undefined symbol error will occur when you are building an executable that depends on
rust-bar-sys. More specifically, all the symbols that libbar.a imports from libfoo.a will be undefined in this case.
OS / Toolchain Versions
This problem seems to only present when targeting ELF (using gcc or clang as the linker frontend, bfd or gold as the linker). Both x86_64 and arm targets are affected.
I believe in this scenario that rust-bar-sys needs to depend on rust-foo-sys (e.g. extern crate rust_foo_sys). Does that fix things for you?
@alexcrichton Thanks for the reply! Unfortunately this was already being done in the example.
There are several individual tweaks that I found to be able to fix this problem but I couldn't understand why:
- Set
rust-bar-sys'scargo:rustc-link-libkindto bestatic. - Remove the
kindoption inrust-foo-sys'scargo:rustc-link-libflag. - Swap the
cargo:rustc-link-libflags inrust-bar-sysso thatlibbarcomes beforelibfoo. (e.g., swap the 3rd and the 4th line here)- This does look like a static library link order issue...
@alexcrichton Cargo currently generates the following linker arguments for the final executable in my example repo, which doesn't seem to be correct:
(...) libbar-sys.rlib libfoo-sys.rlib (...) -l bar
As libfoo.a is statically linked with libfoo-sys.rlib (thus libfoo-sys.rlib contains all the object files from libfoo.a), -l bar really should be placed before libfoo-sys.rlib so that the symbols libbar.a imports from libfoo.a could be resolved.
I can further verify this by switching the linker to lld. Both ld.bfd and ld.gold require the order of the static libraries to be passed correctly to them so this problem is triggered when using those linkers. ld.lld however doesn't require this and I was able to compile my example successfully with it.
Ah ok, thanks for checking! In any case yeah I think this is an upstream rustc issue rather than a Cargo issue, which is just shipping arguments to the compiler.
Closing this since it was moved to rust-lang/rust!