12

How does one compile a Rust application without having to load shared libraries at all?

What have I tried:

ex.rs

fn main() {
  println!("Try to compile me statically!");
}

According to https://rust-lang.github.io/rfcs/1721-crt-static.html I performed the following:

$ rustc -C target-feature=+crt-static ./ex.rs
$ ldd ./ex
    linux-vdso.so.1 (0x00007ffc4e3ef000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fc30b8c4000)
    librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007fc30b6bc000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fc30b49d000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fc30b285000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fc30ae94000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fc30bcfb000)

Why isn't libc compiled statically? And how to get rid of linking all other shared libraries?

3
  • 2
    AFAIK standard libc (like glibc) aren't designed to be linked statically. You can try to use musl instead. Commented Jan 16, 2020 at 9:43
  • @Cerberus But my target project make use of the actix crate, which does not support musl. How to overcome it ? Commented Jan 16, 2020 at 9:45
  • You fork actix or find an alternative Commented Apr 26, 2024 at 5:08

1 Answer 1

13

MUSL support for fully static binaries:
By default, Rust will statically link all Rust code. However, if you use the standard library, it will dynamically link to the system's libc implementation.

If you'd like a 100% static binary, the MUSL libc can be used on Linux:

rustup target add x86_64-unknown-linux-musl 
RUSTFLAGS='-C link-arg=-s' cargo build --release --target x86_64-unknown-linux-musl

main.rs file:

use actix_web::{web, App, HttpServer, Responder};

async fn index(info: web::Path<(String, u32)>) -> impl Responder {
    format!("Hello {}! id:{}", info.0, info.1)
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(web::resource("/{name}/{id}/index.html").to(index)))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}

Cargo.toml file:

[profile.release]
opt-level = 's'  # Optimize for size.
lto = true # Link Time Optimization (LTO)
# codegen-units = 1 # Set this to 1 to allow for maximum size reduction optimizations:
# panic = 'abort' # removes the need for this extra unwinding code.

[dependencies]
actix-web = "2.0.0" # Actix web is a simple, pragmatic and extremely fast web framework for Rust.
actix-rt = "1.0.0"  # Actix runtime

Rust Platform Support

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It seems to be changed since the 2.0 version of actix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.