Creating Static Executables with Rust and glibc: A Guide
Problem: You want to build a static executable in Rust, but you prefer using the widely used glibc standard C library instead of musl.
Rephrased: You're building a Rust program and want it to work on different Linux systems without needing additional libraries installed. However, you want your program to rely on the commonly used glibc library instead of the more lightweight musl.
Let's Dive In:
Creating static executables in Rust usually involves using musl
as the standard C library because it's designed to be statically linked. However, if you need your application to work with glibc, the process requires some additional steps.
The Code:
// example.rs
fn main() {
println!("Hello, world!");
}
Building the Static Executable:
-
Compile with
--target=x86_64-unknown-linux-gnu
: This target ensures you're compiling for a standard glibc-based Linux system.rustc --target=x86_64-unknown-linux-gnu --static example.rs -o example
-
Use
-C link-arg=-static
: This flag tells the linker to use the static version of the standard C library (glibc in this case).rustc --target=x86_64-unknown-linux-gnu --static -C link-arg=-static example.rs -o example
-
Verify the Executable: Run the
file
command on the executable. It should indicate that it's a statically linked ELF binary.file example
Important Considerations:
- Size: Static executables are generally larger than dynamic ones as they include all necessary libraries.
- Compatibility: Statically linked executables may not be compatible with different Linux distributions or versions if the system's glibc version is incompatible.
- Runtime Dependencies: While the executable is static, it still might rely on some system libraries for basic functionalities like process management or memory allocation.
Additional Tips:
- Use
cargo
: Thecargo
build system offers a more convenient way to build static executables. You can set thetarget
andlink-arg
flags in yourCargo.toml
file. - Static Linking with glibc: Using
--static
with glibc can be tricky. You might need to explore specific libraries like "glibc-static" provided by some Linux distributions. - Docker: Creating a Docker container with the desired glibc version can help isolate the environment for building and running your static executable.
Remember: Building static executables comes with trade-offs. Analyze your needs, consider the size and compatibility issues, and choose the best approach for your specific project.
Resources:
This guide provides a comprehensive explanation of how to create static executables in Rust using glibc. By understanding the process and its implications, you can create robust applications with increased portability.