Journal 2023-02-22

C/CPP programming in Nix

NixOS has a lot of advantages to program in C/CPP. The version of each library and compiler is pinned by the nix package manager and each build is reproducible.

The problem begins when you are in a development environment. If you want to compile your project with clang you have to setup the environment correctly. I had problems with just specifying clang as a package in the nix shell:

{
    devShells.x86_64-linux.default = pkgs.mkShell {
        packages = with pkgs; [
            clang
            clang-tools
        ];
    };
}

The problem was that clangd (the LSP) was not able to find the standard library. The best solution was to follow the NixOs wiki Using Clang instead of GCC, but since mkShell gets the stdenv as an inputevent.FootnoteReference, I need to override it. This is what I came up with:

{
    devShells.x86_64-linux.default = pkgs.mkShell.override { inherit (pkgs.llvmPackages) stdenv; } {
        packages = with pkgs; [
            clang-tools
        ];
    };
}
1
[mkShell](https://github.com/NixOS/nixpkgs/blob/fb3a27fade656122e28afde3d8263e933f54ed93/pkgs/build-support/mkshell/default.nix#L1)