Why are Rust executables so huge?

后端 未结 6 1368
醉酒成梦
醉酒成梦 2020-11-30 17:34

Just having found Rust and having read the first two chapters of the documentation, I find the approach and the way they defined the language particularly interesting. So I

6条回答
  •  孤独总比滥情好
    2020-11-30 18:23

    I don't have any Windows systems to try on, but on Linux, a statically compiled Rust hello world is actually smaller than the equivalent C. If you are seeing a huge difference in size, it is probably because you are linking the Rust executable statically and the C one dynamically.

    With dynamic linking, you need to take the size of all the dynamic libraries into account too, not just the executable.

    So, if you want to compare apples to apples, you need to make sure either both are dynamic or both are static. Different compilers will have different defaults, so you can't just rely on the compiler defaults to produce the same result.

    If you're interested, here are my results:

    -rw-r--r-- 1 aij aij     63 Apr  5 14:26 printf.c
    -rwxr-xr-x 1 aij aij   6696 Apr  5 14:27 printf.dyn
    -rwxr-xr-x 1 aij aij 829344 Apr  5 14:27 printf.static
    -rw-r--r-- 1 aij aij     59 Apr  5 14:26 puts.c
    -rwxr-xr-x 1 aij aij   6696 Apr  5 14:27 puts.dyn
    -rwxr-xr-x 1 aij aij 829344 Apr  5 14:27 puts.static
    -rwxr-xr-x 1 aij aij   8712 Apr  5 14:28 rust.dyn
    -rw-r--r-- 1 aij aij     46 Apr  5 14:09 rust.rs
    -rwxr-xr-x 1 aij aij 661496 Apr  5 14:28 rust.static
    

    These were compiled with gcc (Debian 4.9.2-10) 4.9.2 and rustc 1.0.0-nightly (d17d6e7f1 2015-04-02) (built 2015-04-03), both with default options and with -static for gcc and -C prefer-dynamic for rustc.

    I had two versions of the C hello world because I thought using puts() might link in fewer compilation units.

    If you want to try reproducing it on Windows, here are the sources I used:

    printf.c:

    #include 
    int main() {
      printf("Hello, world!\n");
    }
    

    puts.c:

    #include 
    int main() {
      puts("Hello, world!");
    }
    

    rust.rs

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

    Also, keep in mind that different amounts of debugging information, or different optimization levels would also make a difference. But I expect if you are seeing a huge difference it is due to static vs. dynamic linking.

提交回复
热议问题