Dynamic rust executable

Hi everyone,

I am curious about rust executable. I know when I run cargo run command with debug or release mode, under target folder there is an executable. However, when I run the ldd command on that executable it gives the following output;

$ ldd rust_project
	linux-vdso.so.1 =>  (0x00007fffa3312000)
	libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fcf3fb73000)
	librt.so.1 => /lib64/librt.so.1 (0x00007fcf3f96b000)
	libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fcf3f74f000)
	libdl.so.2 => /lib64/libdl.so.2 (0x00007fcf3f54b000)
	libc.so.6 => /lib64/libc.so.6 (0x00007fcf3f17d000)
	/lib64/ld-linux-x86-64.so.2 (0x00007fcf3ffd7000)

Which makes me think is it acting like a static library ? I know if I give this executable to someone else, they can run it even without having Rust installed (at least book says this way). Therefore, it makes sense if it is acting as static.
Is there anyway to make it dynamic. I mean I want to make a common folder of my crates (dependencies) for all my projects and give this path when compiling my project (such as L flag to gcc/g++). Afterwards, without that folder executable should not work? What my goal is reducing the size of executable and make it more environment dependent.

There's -C prefer-dynamic, but it's a bad idea to use it, because it does make executables depend on the Rust compiler, and not just any Rust compiler, but your exact version on your computer. Rust's ABI for Rust-only dynamic libraries is not guaranteed to remain the same between Rust versions.

Rust can dynamically link C libraries that have a stable ABI, and Rust libraries that explicitly export a C ABI, but majority of crates needs to be linked statically, and many (crates that use generics or proc macros) are even logically impossible to ever implement as a dynamic library.

1 Like

I have 2 questions related with this. I couldn't figure it out how to use -C prefer-dynamic flag while creating binary.

  1. When I run my project with cargo run --release, is the executable under ./target/release/rust_project static? If it is working in different environments which don't even have rust downloaded it should be static right?

  2. If it is static, is it possible to make it dynamic? What I mean, I have crates downloaded on my machine and I want to give the path of each crate while running my project with cargo run --release or something like rustc -L /path/of/crates src/main.rs. Ofcourse, with this option, the executable will be dependent on the rust compiler and all of the crates.

Yes

Cargo doesn't support providing externally built crates.

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.