Skip to content

Development with nix

Johannes Maier edited this page Aug 4, 2022 · 26 revisions

Traditional approach

Here is a sample shell.nix for building/developing zig.

with import <nixpkgs> {};

pkgs.mkShell {
  nativeBuildInputs = with pkgs; [
    cmake
    gdb
    libxml2
    ninja
    qemu
    wasmtime
    zlib
  ] ++ (with llvmPackages_14; [
    clang
    clang-unwrapped
    lld
    llvm
  ]);

  hardeningDisable = [ "all" ];
}

The hardeningDisable part is crucial, otherwise you will get compile errors.

Flake

Alternatively, you can use this sample flake.nix:

{
  description = "A flake for Zig development";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
    flake-utils.url = "github:numtide/flake-utils";
    flake-compat = {
      url = "github:edolstra/flake-compat";
      flake = false;
    };
  };

  outputs = inputs@{ self, ... }: inputs.flake-utils.lib.eachDefaultSystem (system:
    let
      pkgs = inputs.nixpkgs.legacyPackages.${system};
    in
      {
        devShells.default = pkgs.mkShell {
          nativeBuildInputs = with pkgs; [
            cmake
            gdb
            libxml2
            ninja
            qemu
            wasmtime
            zlib
          ] ++ (with llvmPackages_14; [
            clang
            clang-unwrapped
            lld
            llvm
          ]);

          hardeningDisable = [ "all" ];
        };
        # For compatibility with older versions of the `nix` binary
        devShell = self.devShells.${system}.default;
      }
  );
}

Notes for macOS users

If using macOS, you will need to build llvm yourself and use the system's clang to build zig. This is possible using the sample shell.nix below.

with import <nixpkgs> { };

pkgs.mkShellNoCC {
  nativeBuildInputs = with pkgs; [ cmake gdb ninja qemu wasmtime ];

  hardeningDisable = [ "all" ];
}