- Creating the rust project:
cargo init gnustatic && cd gnustatic
- Creating
.cargo
configuration directory
mkdir -p .cargo
It creates a hello world by default in src/main.rs
:
fn main() {
println!("Hello, world!");
}
- Adding GNU static linking rules:
[target.x86_64-unknown-linux-gnu] # Adjust this to your target triple
rustflags = [
"-C", "target-feature=+crt-static"
]
So:
echo "[target.x86_64-unknown-linux-gnu] # Adjust this to your target triple
rustflags = [
\"-C\", \"target-feature=+crt-static\"
]" >> .cargo/config.toml
- Adding size optimization options for the binary:
The optimizations:
[profile.release]
panic = "abort"
strip = true
opt-level = "z"
lto = true
codegen-units = 1
Adding:
echo "
[profile.release]
panic = \"abort\"
strip = true
opt-level = \"z\"
lto = true
codegen-units = 1
" >> Cargo.toml
"
- Compile the Hello World binary:
cargo build --target x86_64-unknown-linux-gnu --release
- Check if it is static linked:
file target/x86_64-unknown-linux-gnu/release/gnustatic
ldd target/x86_64-unknown-linux-gnu/release/gnustatic
- Check the size:
$ du -sh target/x86_64-unknown-linux-gnu/release/gnustatic
1.2M target/x86_64-unknown-linux-gnu/release/gnustatic
upx --best --lzma target/x86_64-unknown-linux-gnu/release/gnustatic
- check the size:
$ du -sh target/x86_64-unknown-linux-gnu/release/gnustatic
416K target/x86_64-unknown-linux-gnu/release/gnustatic
- Check if it is static linked:
$ ldd target/x86_64-unknown-linux-gnu/release/gnustatic
not a dynamic executable
$ file target/x86_64-unknown-linux-gnu/release/gnustatic
target/x86_64-unknown-linux-gnu/release/gnustatic: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), statically linked, no section header
Could you extend by adding binary compression with upx?