Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic linking between crates

Tags:

rust

The state of dynamic linking in rust is very confusing to me currently. I can only find old sources that say rust doesn't support dynamic linking, yet I know multiple libraries that do dynamic linking (ex bevy_dylib).
Is it currently possible to create a bin crate and a lib crate, and link the bin to the lib at runtime using dylib or rlib?
Something like

// lib.rs
fn hi() {
   println!("hi");
}


// main.rs
fn main() {
   // whatever to link to lib.rs/lib.so
   link("./lib.so");
   hi();
}
like image 946
salmon Avatar asked Jan 18 '26 08:01

salmon


1 Answers

To link dynamically instead of statically the only thing you have to change is the crate type of your library from the default to dylib:

Generate a library:

cargo new --lib dy-lib

Add the type in dy-lib/Cargo.toml everything else can stay unchanged:

[lib]
crate-type = ["dylib"]

Generate a binary and add library as dependency:

cargo new dy-bin
cd dy-bin
cargo add dy-lib --path ../dy-lib

Replace the contents of dy-bin/src/main.rs with something that uses the library:

fn main() {
    println!("{}", dy_lib::add(1, 2));
}

build the binary

cargo build # or cargo run, ...

The binary is now dynamically linked to our dynamic library as can be seen by for example readelf on linux:

$ readelf -d target/debug/dy-bin

Dynamic section at offset 0x2d70 contains 30 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libdy_lib.so]
...

And if you remove it there will be a runtime error:

$ rm target/debug/libdy_lib.so
$ target/debug/dy-bin
target/debug/dy-bin: error while loading shared libraries: libdy_lib.so: cannot open shared object file: No such file or directory
like image 55
cafce25 Avatar answered Jan 21 '26 07:01

cafce25