.TL Nix Cook Book .AU tropf .AB My personal recipes when using .URL "https://nixos.org/" "nix" "." .AE .DA . .NH 1 Intro .PP Nix refers to the operating system NixOS, the package manager and associated repository nixpkgs, and the functional language nix itself. I use all three, because I like its focus towards reproducability. .PP It declarative approach breaks with many habits and also tools, so in this document I attempt to make some notes how to tackle challenges I encountered in using nix. . .NH 1 Parameterized Packages in Flakes .PP To create multiple versions of the same package (derivation) with different parameters use \fCcallPackage\fR. Note the trailing \fC{}\fR to immedeately create a valid derivation. .CB mypkg = pkgs.callPackage ({doCheck ? false}: stdenv.mkDerivation rec { inherit doCheck; checkTarget = "test"; cmakeFlags = (if doCheck then [ "-DBUILD_TESTING=TRUE" ] else []); }) {}; mypkg_with_tests = selfpkgs.mypkg.override {doCheck = true;}; .CE . .NH 1 Include nix CFLAGS in Exported Compile Commands .PP When exporting cmake compile commands the nix-defined compiler flags (stored in environment variables) will not be included. You can manually add them with a (hacky) sed command. .NOTE "This modifies JSON with sed and is evil. Use at your own risk." .CB nix develop && cd build cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON . sed -e "s,$(which g++),$(which g++) $NIX_CFLAGS_COMPILE,g" -i compile_commands.json # note: this is maybe already called automatically by your editor rc -J . .CE . .NH 1 Creating Debuggable Builds .PP By default, nix will enable all sorts of optimizations/security options ("fortifications") in C/C++ programs. This can make debugging very hard, as it optimizes code out/reorders your code, even using .CW "Debug" cmake build type. .PP To disable these modifications set: .CW "hardeningDisable = [ \[dq]all\[dq] ]" .br In full context this may be used as such: .CB buildInputs = [ cmake gcc ] ++ (if doCheck then [ catch2 cmakeCurses gdb ] else []); cmakeFlags = (if doCheck then [ "-DBUILD_TESTING=TRUE" "-DCMAKE_BUILD_TYPE=Debug" ] else []); hardeningDisable = if doCheck then [ "all" ] else []; .CE . .NH 1 Build without Tests, but Develop with Tests .PP You can specify different targets for .CW "nix build" and .CW "nix develop" such that they refer to different deviations: .CB defaultPackage.x86_64-linux = mypkg; devShells.x86_64-linux.default = mypkg_with_tests; .CE . .NH 1 Ensure Locales Exist .PP The CI infrastructure I use lacks some locales. When building plots etc., the font handling doesn't work due to these missing locales. Disturbingly, my local .CW "nix build" invocation finds the locales and looks completely fine, while the CI version does not. To fix this set the following variables inside the .CW "stdenv" invocation: .CB LOCALE_ARCHIVE = "${glibcLocales.override {allLocales = false; locales=["en_US.UTF-8/UTF-8"];}}/lib/locale/locale-archive"; LC_ALL = "en_US.utf8"; .CE