Code size for hello world Rust vs. C


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?


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


Oh I see. I will


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


opt-level = 3
strip = true
debug = false
lto = true
codegen-units = 1

C code:

#include <stdio.h>

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

Rust code:


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

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.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.