Using Rust Library via C-FFI from Rust

In am building a Rust library that I distribute as a compiled static C-Library (.a).
Now I have a client that wants to use Rust. Unfortunately we can not distribute the source code, so we have to deliver the compiled C-Library.

When I build the Rust-FFI with one Rust version and the lib.a contains the Rust std library, I can not integrate this lib.a in a Rust program that was build with a different Rust version.

I get an error that rust_eh_personality is defined multiple times:

Linking with CC failed

  = note: /usr/bin/ld: /home/stephan/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd-099ea48a26be4ce8.rlib(std-099ea48a26be4ce8.std.da76efc55aba569b-cgu.0.rcgu.o): in function `rust_eh_personality':
          /rustc/29483883eed69d5fb4db01964cdf2af4d86e9cb2/library/std/src/sys/personality/gcc.rs:297: multiple definition of `rust_eh_personality'; /home/stephan/Development/aic/aic-sdk-rs/target/debug/deps/libaic_sdk_sys-6fc009c104738955.rlib(std-f6265b21db1f990f.std.d9e466a2d75004a2-cgu.0.rcgu.o):/rustc/05f9846f893b09a1be1fc8560e33fc3c815cfecb/library/std/src/sys/personality/gcc.rs:294: first defined here
          cc: error: linker command failed with exit code 1 (use -v to see invocation)

Does anyone know a solution to the problem besides using no_std?

The rust_eh_personality is for unwinding. Theoretically it shouldn't be needed if you build with panic=abort, but you may also need to build with -Zbuild-std,panic_immediate_abort to get rid of it from the standard library.

However, .a is meant for C programs. Rust programs need the .rlib format to get metadata to link smarter, but unfortunately that requires using exactly the same compiler version.

Rust/Cargo is heavily biased by open-source code distribution, and just doesn't have features necessary to consume pre-built code without jumping through hoops.

Another option is to build cdylib (so/dll) dynamic library, which will have its own copy of libstd. However, Rust doesn't have a stable ABI (you'd need C ABI or crates like abi-stable). Cargo doesn't support dynamic library deps well, so you'd need a wrapper sys crate and some external packaging system to get and install it.

1 Like

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.