[package]
name = "static-rust-library"
version = "0.1.0"
edition = "2021"
[dependencies]
[lib]
name = "static_rust_lib"
crate-type = ["staticlib"]
However, when trying to link the library quite a few libraries are required:
$ cargo rustc -q -- --print=native-static-libs
note: Link against the following native artifacts when linking against this static library. The order and any duplication can be significant on some platforms.
note: native-static-libs: kernel32.lib advapi32.lib kernel32.lib ntdll.lib userenv.lib ws2_32.lib kernel32.lib ws2_32.lib kernel32.lib msvcrt.lib
Can I reduce the number of those dependencies? Why winsock library is needed?
The required native libraries are a property of the target triple. I suspect you're targeting x86_64-pc-windows-msvc. Sockets are linked to because the standard library provides socket functionality, and the system support needs to be present for that; std is imported as a single unit and all of its dependencies are requested if any of it is.
Building with #![no_std] so that only core and not std is available may remove some system dependencies. But in return, you lose any functionality that uses the hosted OS functionality, such as stdout.
The Rust parts of std are largely optimized out in a coarse manner (what symbols are reachable) by the static linking process, but the system library linkage is coarse and only based on crate linkage; there's no record of what symbols come from what library from which to figure out which dependencies aren't really necessary. The assumption of the target is that the OS is present and linking to the basic OS libraries is something not unreasonably burdensome.
Windows could maybe do a bit better, since it's possible for PE files to specify to link "this item from this library" instead of just specifying symbol names without further context, but note that Microsoft has specific rules about how linking is allowed to be done if you want to actually be supported, and generally that means doing it the straightforward way that msvc does and not trying to be overly clever with it.
Once we switch the standard library to raw-dylib I did expect the generated import libraries embedded in the staticlib to completely replace all explicit linker arguments for importing standard library system dependencies. For user crates you may still need to respect native-static-libs though.