22

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Thomas Bratt
  • 48,038
  • 36
  • 121
  • 139

2 Answers2

17

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Matt Harrison
  • 13,381
  • 6
  • 48
  • 66
  • Nice :) I'll accept that as the answer unless someone comes up with something definitive from the rust docs/project. – Thomas Bratt Aug 28 '18 at 12:31
9

TL;DR: Yes, every unused function is going to be excluded.

This is actually the job of LLVM that will at least keep track of every unused function. Any unused code (as in codepaths in function not taken across the entire Application) may require LTO (Link Time Optimizations) to be activated to turn your crate into one compilation unit and give LLVM a fighting chance.

Markus Klein
  • 1,202
  • 12
  • 10