Kevin De Baerdemaeker

Nixpkgs

Modified 2024-09-11

Nix expressions describe how to build packages from source.

When buildInputs vs nativeInputs?

nativeBuildInputs

programs and libraries used at build-time

buildInputs

programs and libraries used by the derivation at run-time*

Building Packages (simple)

Using nix develop starts the default devShell from the flake.

Running nix build builds the default package from the flake. Running nix run, builds and runs the default package from the flake. These two commands run in an isolated environment, so packages available in nix develop won't be available here.

{
  description = "Hello World from Nix & C";
  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixos-23.11";
  };

  outputs = { self, nixpkgs }:
  let
    system = "aarch64-linux";
    pkgs = nixpkgs.legacyPackages.${system};
  in
  {
    devShells.${system}.default = pkgs.mkShell {
      # adds gdb to use for debugger
      packages = [
        pkgs.gdb
      ];

      # adds the build dependencies from myHello to the shell
      inputsFrom = [
        self.packages.${system}.myHello
      ];
    };

    packages.${system} = {
      myHello = pkgs.stdenv.mkDerivation {
        pname = "my-hello";
        version = "v0.0.1";
        src = ./src;

        # compiles the program
        buildPhase = ''
          gcc hello.c -o my-hello
        '';

        # by default `nix run` looks into ./result/bin folder
        # and runs the pname
        installPhase = ''
          mkdir -p $out/bin
          cp my-hello $out/bin/
        '';
      };
      default = self.packages.${system}.myHello;
    };
  };
}

References


Backlinks