Building Rust packages against musl

Is it possible to build a completely statically-linked rust binary against musl using buildRustPackage? I have added target = "x86_64-unknown-linux-musl"; to the buildRustPackage call in my flake, and running ldd on the binary in result/bin/ still shows it as being dynamically linked to GLIBC.

flake.nix
{
  inputs.nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";

  outputs = { self, nixpkgs, }:
    let
      supportedSystems = [ "x86_64-linux" ];

      # Helper function to generate an attrset '{ x86_64-linux = f "x86_64-linux"; ... }'.
      forAllSystems = nixpkgs.lib.genAttrs supportedSystems;

      # Nixpkgs instantiated for supported system types.
      nixpkgsFor = forAllSystems (system: import nixpkgs { inherit system; });
    in
    {
      packages = forAllSystems (system:
        let pkgs = nixpkgsFor.${system};
        in {
          default = pkgs.rustPlatform.buildRustPackage rec {
            pname = "hello";
            version = "0.0.1";

            target = "x86_64-unknown-linux-musl";

            src = ./.;
            cargoLock = {
              lockFile = ./Cargo.lock;
            };
          };
        });

      devShells = forAllSystems (system:
        let pkgs = nixpkgsFor.${system};
        in {
          default = pkgs.mkShell {
            buildInputs = with pkgs; [
              cargo
              rustc
              rustfmt
            ];
          };
        });
    };
}
2 Likes

Short answer: pkgsStatic

Example flake below. Create the project with cargo init --name rust-musl-hello . from within a nix develop shell on this same flake.

{
  description = "Hello world Rust program statically linked against musl";

  inputs.nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";

  outputs = { self, nixpkgs, }:
    let
      # Should work with other targets, but not tested.
      supportedSystems = [ "x86_64-linux" ];

      # Helper function to generate an attrset '{ x86_64-linux = f "x86_64-linux"; ... }'.
      forAllSystems = nixpkgs.lib.genAttrs supportedSystems;

      # Nixpkgs instantiated for supported system types.
      nixpkgsFor = forAllSystems (system: import nixpkgs { inherit system; });
    in
    {
      packages = forAllSystems (system:
        let
          pkgs = nixpkgsFor.${system}.pkgsStatic;
        in {
          default = pkgs.rustPlatform.buildRustPackage rec {
            pname = "rust-musl-hello";
            version = "0.1.0";

            src = ./.;
            cargoLock = {
              lockFile = ./Cargo.lock;
            };
          };
        });

      devShells = forAllSystems (system:
        let pkgs = nixpkgsFor.${system};
        in {
          default = pkgs.mkShell {
            buildInputs = with pkgs; [
              cargo
            ];
          };
        });
    };
}
5 Likes