Is there anyway I could compile a Rust program to a binary which does not depend on a libc for runtime and for Linux?
If we put no_std
or bare metal development with Rust (like writing a kernel or firmware) aside you can't compile Rust without dependency on some libc. But you can statically link musl with your Rust program and therefore you won't need an external libc for your Rust program to run. musl should work on any kernel newer than 2.6.39:
Linux 2.6.39 or later is believed to be sufficient; earlier versions in the 2.6 series will work, but with varying degrees of non-conformance, particularly in the area of signal handling behavior and close-on-exec race conditions. https://musl.libc.org/doc/1.1.24/manual.html
(Since it says kernel 2.6.39 and above, probably the binary will also work on Android devices. They typically use kernel 3.x or 4.x Though I haven't checked this myself)
To achieve this, first you have to install the rust toolchain with musl and Linux. There is complete list of Rust toolchains and their tiers [here](https://doc.rust-lang.org/nightly/rustc/platform-support.html). At the time of writing this answer, no toolchain with musl as libc is Tier 1. However there are multiple linux-musl` toolchains for different architectures in Tier 2. In my experience, unless your program or requirements are too specific, Tier 2 platforms work well. Then you use rustup to install the desired toolchain:
rustup toolchain install stable-aarch64-unknown-linux-musl
The command above installs the stable version of Linux with musl for 64 bit ARM. This is given that your host machine is also aarch64. If not, you probably want to cross compile. You add the target for this purpose:
rustup target add aarch64-unknown-linux-musl
Now in your project with cargo, you can specify the target when using cargo build
:
cargo build -r --target aarch64-unknown-linux-musl
Depending on the host and target, you might also be to change the default toolchain. For instance I want to create binaries for ESP32:
rustup default esp
Then to see which toolchain is active:
$ rustup toolchain list
stable-x86_64-unknown-linux-gnu
nightly-x86_64-unknown-linux-gnu
1.64.0-x86_64-unknown-linux-gnu
1.77-x86_64-unknown-linux-gnu
1.77.2-x86_64-unknown-linux-gnu
esp (active, default)