Hello! I want to create a shared library out of a Rust crate, one that I can load/dlopen() later in one my C++ projects (practically a plugin). To do that, I am using the cdylib crate-type.
[lib]
crate-type = ["cdylib"]
Creating the library works properly. The part where I'm having problems with is the library size which is bigger than I expected. Previously to converting the crate to a library, I used it as a binary, which had a smaller size that I was OK with. I have the following reduced example:
Cargo.toml
[lib]
crate-type = ["lib", "cdylib"]
[profile.release]
codegen-units = 1
lto = true
opt-level = 'z'
panic = 'abort'
src/main.rs
fn main() {
foo::do_something();
}
src/lib.rs
#[no_mangle]
extern "C" fn the_symbol() {
do_something()
}
pub fn do_something() {
println!("hello");
}
With this example, cargo builds both a binary and a library out of the same code.
Binary size
$ strip -s target/release/foo && ls -lh target/release/foo && ldd target/release/foo
-rwxr-xr-x. 2 master master 231K Sep 9 11:09 target/release/foo
linux-vdso.so.1 (0x00007ffc7cd90000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f10f322e000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f10f3213000)
libc.so.6 => /lib64/libc.so.6 (0x00007f10f3049000)
/lib64/ld-linux-x86-64.so.2 (0x00007f10f32b7000)
Library size
$ strip -s target/release/libfoo.so && ls -lh target/release/libfoo.so && ldd target/release/libfoo.so
-rwxr-xr-x. 2 master master 263K Sep 9 11:10 target/release/libfoo.so
linux-vdso.so.1 (0x00007ffc23fc0000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007fc977d04000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fc977ce2000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fc977cc7000)
libc.so.6 => /lib64/libc.so.6 (0x00007fc977afd000)
/lib64/ld-linux-x86-64.so.2 (0x00007fc977d7a000)
As you can see, there is a difference of 32K between the binary and library. In the project I am working on, the difference is bigger:
Stripped binary and library
$ ls -lh target/release/libbar.so target/release/bar
-rwxr-xr-x. 2 master master 439K Sep 9 11:13 target/release/bar
-rwxr-xr-x. 2 master master 559K Sep 9 11:13 target/release/libbar.so
And when I'm also using Xargo, the difference is even more noticeable:
Xargo.toml
[dependencies]
std = {default-features=false, features=["panic_immediate_abort"]}
Stripped binary and library
$ ls -lh target/x86_64-unknown-linux-gnu/release/libbdsetter.so target/x86_64-unknown-linux-gnu/release/bdsetter
-rwxr-xr-x. 2 master master 163K Sep 9 11:18 target/x86_64-unknown-linux-gnu/release/bdsetter
-rwxr-xr-x. 2 master master 299K Sep 9 11:18 target/x86_64-unknown-linux-gnu/release/libbdsetter.so
Where is this difference coming from? Is it possible to reduce the library size to match the one of the binary? Might be related to https://github.com/rust-lang/rust/issues/37530, but I'm still not sure if there's any solution for my problem.