C++ Development with Nix

Nix is a package manager for Linux and other Unix systems. It allows people to get reliable and reproducible builds. It also allows to easily share complex software. With Nix it is no problem to have several different C compilers and several different versions of the same library installed on one system.

In this post, I want to document how I use Nix to develop C++ applications. If you never heard of Nix, you better read first about it here.

I have created a little sample project here. The project uses CMake and Ninja for building and creates a small window with the help of the GLFW library. The application just shows a yellow window.

If you clone the project, you can build the entire project with one straightforward command:

nix-build

This will pull all the dependencies to build the project.

This is how my default.nix looks like:

{
  nixpkgs ? (builtins.fetchGit {
    name = "nixos-unstable-2020-11-25";
    url = "https://github.com/nixos/nixpkgs-channels/";
    # `git ls-remote https://github.com/nixos/nixpkgs-channels nixos-unstable`
    ref = "refs/heads/nixos-unstable";
    rev = "84d74ae9c9cbed73274b8e4e00be14688ffc93fe";
  })
}:

with import nixpkgs {};

stdenv.mkDerivation {
  name = "test_nix_cpp";
  src = ./.;

  nativeBuildInputs = [ cmake ninja ];
  buildInputs = [ glfw ];

  configurePhase = "cmake -G Ninja .";
  buildPhase = "ninja";
  installPhase = ''
    mkdir -p $out/bin
    cp src/tnc $out/bin/
  '';
}

If you want to run the application, you can do so with:

./result/bin/tcn

What about developing? For developing, I use nix-shell. Simply run nix-shell, and you will be dropped into a sort of virtual environment where all the dependencies for the project are setup. So you can now build the project as you would typically do on other systems like:

mkdir build
cd build
cmake -G Ninja ..
ninja

Also, you can run your favourite editor from this environment like:

emacs &

It’s cool to have GLFW and other dependencies just in the virtual environment. No cluttering of my system and the best thing is that if I want to share my program with someone, I can tell them that they need only install Nix and then they can simply run nix-build, to test out my program.

I can recommend the following articles to learn more about Nix:

  • For a great introduction to Nix: NixPills
  • Jaceks’s blog post about developing in C++ with Nix.