Setting NIX_CFLAGS_COMPILE and NIX_CFLAGS_LINK for a subset of packages

I have a set of packages for which I need to apply specific compilation and linking flags. How can I apply these flags to a set of packages so that I do not have to:

stdenv.mkDerivation {
  # ...
  env.NIX_CFLAGS_COMPILE = "-someflag";
  # ...
}

for each package? The answer seems to be to use an overlay on nixpkgs, but documentation is scarce and examples even more so. I have tried the following overlays:

myOverlay = self: super: {
  stdenv = super.stdenvAdapters.addAttrsToDerivation {
      NIX_CFLAGS_COMPILE = "-someflag";
  } super.stdenv;
};

returns the error: The ‘env’ attribute set cannot contain any attributes passed to derivation. The following attributes are overlapping: NIX_CFLAGS_COMPILE.

myOverlay = self: super: {
  stdenv = super.stdenv.overrideDerivation (oldAttrs: {
    env.NIX_CFLAGS_COMPILE = oldAttrs.env.NIX_CFLAGS_COMPILE + " -someflag";
  });
};

returns the error: attribute ‘targetPlatform’ missing. So it seems like I have overridden more than just NIX_CFLAGS_COMPILE in this case.

myOverlay = self: super: {
  stdenv = super.withCFlags ["-someflag"] super.stdenv;
};

works, but now I have no way to set linker flags. I also tried config.replaceStdenv as follows:

pkgs = import sources.nixpkgs {
  config.replaceStdenv = {pkgs}: pkgs.withCFlags ["-someflag"] pkgs.stdenv;    
  # overlays = [
  #   myOverlay
  # ];
};

which I would expect to have the same effect as the previous attempt however, during building GNU hello, this crashes with configure: error: C compiler cannot create executables.

I am quite lost on how to proceed at this point and feel like I am basically just guessing my way to a solution.

1 Like