Code size for hello world Rust vs. C

Hi

I write a code to print out "Hello world" in Rust and C to compare binary size. by the way, binary size compiled with rustc is too bigger than in C.

I found there are many symbols in Rust binary and it looks like name mangling on C++.

Can you please explain why and how to reduce binary size?

BR.

Have you searched? This has been posted many times before, and the answer has not changed.

4 Likes

Oh I see. I will

Thanks.

Yes. First of all, you’re probably using different ways. Secondly, did you build with size optimizations?

Profile:

[profile.release]
opt-level = 3
strip = true
debug = false
lto = true
codegen-units = 1

C code:

#include <stdio.h>

main() {
    puts("Hello, World!");
}

Rust code:

#![no_main]

extern {
    fn puts(ptr: *const u8);
}

#[no_mangle]
unsafe extern fn main() {
    puts("Hello, World!\0".as_ptr());
}

Rust code seems to be more verbose, does it mean bigger binary size? no, it doesn’t

Let’s build our C code with GCC with -O3 flag and our Rust code with -r flag.

On windows, GCC gave me 48 kilobytes, while rustc gave 11 kilobytes. Interesting result, huh?

You probably were getting bigger binaries because of unwinding, allocations and all the stuff that std does :wink:

Or just the fact that Rust links statically by default for reliability, whereas most modern systems provide a dynamic C standard library and so C compilers tend to link it dynamically.

5 Likes