Binary is way bigger on linux than on macOS


#1

I have noticed that binaries on linux (fedora & ubuntu) resulted from cargo build --release is way bigger than them on macOS. for example compiling this package on linux results in 4.8M but on my macOS it’s just 1.4M.

Is there a reason for this to happen, and how can I achieve that small size binary on linux?


#2

I don’t have an answer to the difference, but on how to optimize read https://lifthrasiir.github.io/rustlog/why-is-a-rust-executable-large.html.


#3

It may be that the linux build uses more static linking, so it’s embedding more code in the binary? Is there much difference when you see what libraries are linked to dynamically using ldd?

I tried this out on my laptop with that repo and cross-compiling with cross for both windows and linux (I don’t have access to a mac, and cross doesn’t yet support x86_64-apple-darwin).

$ cross build --target x86_64-unknown-linux-gnu --release
$ du -h target/x86_64-unknown-linux-gnu/release/echo
6.1M	target/x86_64-unknown-linux-gnu/release/echo
$ ldd target/x86_64-unknown-linux-gnu/release/echo  
	linux-vdso.so.1 (0x00007ffe1cbbc000)
	libdl.so.2 => /usr/lib/libdl.so.2 (0x00007fbd47ce1000)
	librt.so.1 => /usr/lib/librt.so.1 (0x00007fbd47ad9000)
	libpthread.so.0 => /usr/lib/libpthread.so.0 (0x00007fbd478bb000)
	libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x00007fbd476a4000)
	libc.so.6 => /usr/lib/libc.so.6 (0x00007fbd472ec000)
	/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007fbd48227000)

$ cargo rustc --release -- -C lto
$du -h target/release/echo
4.5M	target/release/echo

# compiling to x86_64 windows
$ cross build --target x86_64-pc-windows-gnu --release
$ du -h target/x86_64-pc-windows-gnu/release/echo.exe
8.5M	target/x86_64-pc-windows-gnu/release/echo.exe

So the windows binary turns out to be twice as big as the linux one. This makes things really interesting…

It may be useful to ask on the internal forum, seeing as a lot of people who work on rustc hang out there.


#4

It’s the bloat from debug symbols (which Rust adds even in release mode). Bug: https://github.com/rust-lang/rust/issues/46034

Run strip and both will shrink down to 1.1MB.


#5

strip did the trick indeed. thnx man