Cross compilation
- Rust course
- Expert
- Lesson 38/46
- 4 min
Cross-compile with the cross tool.
Cross compilation
Rust can compile on one machine for another platform. A target is named with a triple: arch-vendor-system-abi. The standard library is downloaded for the target; linking needs a suitable linker:
$ rustup target add aarch64-unknown-linux-gnu
$ cargo build --release --target aarch64-unknown-linux-gnu
# .cargo/config.toml
[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"The cross tool reduces this to a single command, using containers that already hold the needed linker and libraries.
Code per target
Code can look at the target's properties with cfg:
#[cfg(target_os = "windows")]
const AYRAC: char = '\\';
#[cfg(not(target_os = "windows"))]
const AYRAC: char = '/';
println!("{}", usize::BITS); // 64 on a 64-bit system
println!("{}", cfg!(target_pointer_width = "64")); // true
println!("{}", std::env::consts::OS); // "linux", "windows", ..rustc --print cfg --target <triple> lists all cfg values of a target.
Practice Target information
Print usize::BITS and cfg!(target_pointer_width = "64") separated by a space (64-bit exercise environment).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
println!("{} {}", usize::BITS, cfg!(target_pointer_width = "64"));
}Expected output
64 true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the advantage of the <code>x86_64-unknown-linux-musl</code> target?
- No advantage
- It produces a fully statically linked binary independent of the glibc version Correct answer
- It's always faster
- It runs on Windows
Explanation: It's often chosen for single-file distribution and small containers.
2 Add a target
$ rustup target ____ aarch64-unknown-linux-gnu
$ rustup target add aarch64-unknown-linux-gnu
Explanation: rustup target add downloads a target's standard library.
3 Triple and platform
| Term | Meaning |
|---|---|
x86_64-pc-windows-msvc |
Windows |
aarch64-apple-darwin |
Apple Silicon macOS |
x86_64-unknown-linux-musl |
Static Linux |
wasm32-unknown-unknown |
WebAssembly |