Rust programming
Install and rustup
- rustup: toolchain manager
- rustc: compiler
- cargo: build & package manager
- crate: smallest compilation unit in Rust (lib/bin)
- crates.io: rust's official package registry
| load rust into shell | |
|---|---|
rust toolchain
A toolchain is a complete Rust environment consisting: - rustc - cargo - Rust standard library - optional components (clippy, rustfmt)
rustup
rustup manages Rust versions, targets, and components on your system.
autocomplete
Add rustup autocomplete
update
update and upgrade toolchain and components
Components
A component is an optional tool that plugs into a Rust toolchain.
- rustfmt: Formatting
- clippy: Linting
Hello world
Simple hello world build and run
- Add aarch target and build it for ARM
Add target (cross compile)
Cross compilation builds a binary for a different CPU or OS than the machine
running cargo build.
Rust needs two things:
- Rust target: standard library for the target platform.
- Linker / C toolchain: only needed when the crate links C code, system libraries, or uses a target that needs an external linker.
Target name format:
Common Linux targets:
| Target | Use case | libc | Static friendly |
|---|---|---|---|
x86_64-unknown-linux-gnu |
normal Linux x86_64 | glibc | partial |
aarch64-unknown-linux-gnu |
64-bit ARM Linux | glibc | partial |
x86_64-unknown-linux-musl |
portable Linux x86_64 | musl | yes |
aarch64-unknown-linux-musl |
portable 64-bit ARM Linux | musl | yes |
GNU target example: build for ARM64 Linux
GNU targets use glibc. The binary usually depends on shared libraries from the target system.
| install rust target | |
|---|---|
| build with aarch target | |
|---|---|
The output binary will be here:
Check the binary:
musl target: create static Linux binary
musl is an alternative C standard library.
Why use musl:
- Produces mostly or fully static Linux binaries.
- Easier to copy one executable to another Linux machine.
- Good for containers, small deployments, and servers without matching glibc.
Install musl tools:
Add the Rust musl target:
| x86_64 static binary target | |
|---|---|
Build:
| build static binary | |
|---|---|
Output:
Check if the binary is static:
For a static binary, ldd usually prints:
ARM64 static binary with musl
For ARM64 Linux:
On Ubuntu/Debian, the native musl-tools package usually gives a musl compiler
for the host architecture. For cross-compiling musl to ARM64, the easiest
practical option is often cross, which builds inside a prepared container.
Install cross:
Build:
Output:
Strip and reduce binary size
Strip debug symbols:
Or configure release builds in Cargo.toml:
Important notes
- Pure Rust crates are easiest to cross compile.
- Crates using C libraries may need matching target libraries and headers.
musl-toolsis the musl compiler package on Ubuntu/Debian.crossis usually simpler when building for another CPU architecture.- Use
fileandlddto verify what kind of binary was produced.