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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With