I am new to the rust language. When i compare my rust hello world program binary with c/c++ hello world program binary i found huge size difference. My rust binary size is 3.1MB and c/c++ binary size is 128KB. I tried google to know why the the size is so huge. And i come to know that rust by default do the static linking due to this the size is increasing. Can any one please correct me if i am wrong. And if this the case please tell me how can i reduce my binary size for hello world program. Using cargo i tried both develop and release binary and in both the case the binary size is 3.1MB.
Have you already had a look at this StackOverflow post?
https://stackoverflow.com/a/29008355/7317517
I think it sums up the point pretty well.
I have recently shipped a stand-alone binary application in Rust and I found that if you want to look into optimizing your binary size, min-sized-rust is a good starting point.
@MaximilianKoestler thank you very much for your help. Now i am able to create my binary with 1.2MB. Now all most it reduced to around 70% after adding below option in Cargo.toml which one i found from you git hub.
[profile.release]
opt-level = 'z' # Optimize for size.
lto = true # Enable Link Time Optimization
codegen-units = 1 # Reduce number of codegen units to increase optimizations.
panic = 'abort' # Abort on panic
Can you please tell me how can i pass this option from command line means if i want to compile using "rustc <file.rs>" .In this case how can i pass the options.
You can run cargo build -v
to see the options that Cargo passes to rustc. They will include something like this:
rustc -C opt-level=z -C lto -C codegen-units=1 -C panic=abort
Thank you very much. Really very much helpful.
Can you elaborate on why you want to compile directly with rustc
instead of cargo build
?
You can pass compiler flags to rustc
from cargo
via a dedicated config file, which I have found to be a superior solution when compared to calling rustc
directly in most cases.
@MaximilianKoestler Yes i fully agree with you that using cargo is the best solution. But just i wanted to know how to pass with out config file. Now i got my answer. Thank you.
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.