Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a compiled Rust executable exclude unused code from dependencies?

If I build a Rust application using Cargo with some crate dependencies, will any code in those dependencies that is unused by my application be eliminated from the final executable?

like image 668
Thomas Bratt Avatar asked Aug 28 '18 11:08

Thomas Bratt


1 Answers

It looks like it. I made a test lib and bin crate side by side:

// hellobin/src/main.rs

extern crate hellolib;

fn main() {
    hellolib::func1();
}

For the lib:

// hellolib/src/main.rs

pub fn func1() {
    println!("Hello, world!");
}

pub fn func2() {
    println!("Hello, other world!");
}

Building my binary and then inspecting symbols with nm:

$ nm target/debug/helloworld | grep hello
0000000100001360 t __ZN10helloworld4main17h749f61fb726f0a10E
00000001000014b0 T __ZN8hellolib5func117hec0b5301559d46f6E

Only the used function has a symbol in the final binary.

You can compile with cargo rustc -- -C link-dead-code though and you will see both symbols are present, including the unused one:

$ nm target/debug/helloworld | grep hello
0000000100001270 t __ZN10helloworld4main17h3104b73b00fdd798E
00000001000013d0 T __ZN8hellolib5func117hec0b5301559d46f6E
0000000100001420 T __ZN8hellolib5func217hc9d0886874057b84E

I believe (but I'm not sure) that it's the linker removing the dead code, so it may have still been compiled and then removed during linking.

like image 66
Matt Harrison Avatar answered Dec 13 '22 11:12

Matt Harrison