Optimization levels

Looking to confirm my understanding from looking through nixpkgs. It seems that a particular -On flag is not imposed on all packages, but they are in general determined by the package being compiled.

For example if I do nix log on the hello package I can see -O2 in the build logs, which appears to be set in ./configure. There’s no flag set in the corresponding default.nix.

Presumably I could globally (attempt to) set an optimization level with $NIX_COMPILE_CFLAGS set somewhere in stdenv?

In general as a C++ developer I’m a bit worried that if I compile half a dozen libraries with different -O settings, then build my project against that, the linker might end up selecting a non-optimised instantiation of a particular template function.

1 Like

I think this is pretty common to mix -O0, -O1, -O2 in distros. Different packages may need different optimizations depending on how hot their code is. You can always override this with different NIX_CFLAGS_COMPILE will override those other flags though, so you can do an overlay like this:

self: super: {
  stdenv = super.stdenvAdapters.addAttrsToDerivation {
  } super.stdenv;

Of course that’s a mass rebuild!


-O2 is in defaults due to

hardeningCFlags+=('-O2' '-D_FORTIFY_SOURCE=2')