Building only specific targets with CMake

Is there any way to use only specific CMake targets when building a derivation? In essence it’s something like cmake -B build/ -S . && cmake --build --target foo. A use case may be a package with multiple targets (e.g. docs), only some of them are useful to build (e.g. if docs take noticeable time to build). I haven’t managed to find such examples in Nixpkgs, but maybe I missed them.

The stdEnv has different phases with default values (AFAIK when cmake is present in the nativeBuildInputs attribute the build phases are set so that it ‘just works’ for the standard case) which you can override. In your case, just provide a configurePhase and buildPhase attribute to you derivation. Like that

stdenv.mkDerivation {
  name = "foo";
  ...
  configure phase = "
    cmake -B build/ -S .
  ";
  buildPhase = ''
     cmake --build --target bar -j$NIX_BUILD_CORES
  '';
}

Not tested, but should point you in the right direction.

See https://ryantm.github.io/nixpkgs/stdenv/stdenv/#sec-stdenv-phases

Thanks for your answer! cmake in nativeBuildInputs indeed brings its own hooks and settings (like enableParallelBuilding = true etc). What I’d like to do can certainly be done with manual phase specifications (in my case only buildPhase has to be overriden), but I was looking for a more “built-in” solution, like with cmakeDir and cmakeBuildType.

CMake setup hook does not currently affect any phases other than configure phase. There is a proposal to have it also handle checkPhase but for now, it just uses either make (or ninja when present) for buildPhase.

So you can just list the targets in buildFlags (apparently, ninja setup hook lacks build-specific flags variable at the moment – ninjaFlags is shared by other phases).

Just note that if install target depends on flags you did not list during build, they will be built in installPhase anyway.

2 Likes

Thank you very much for your answer! This is exactly what I was looking for! Then buildFlags it is (the software I’m building is not that large to profit from ninja instead of make).