Can't compile a simple FORTRAN program that uses the HDF5 library

I’m trying to compile a (very) simple Fortran program that uses the HDF5 library:

program test

  use hdf5

end program test

If I try to compile this program with gfortran inside a nix-shell, I get the following error:

% nix-shell -p hdf5-fortran gfortran
% gfortran test_hdf5.f90
test_hdf5.f90:3:6:

    3 |   use hdf5
      |      1
Fatal Error: Cannot open module file ‘hdf5.mod’ for reading at (1): No such file or directory
compilation terminated.

Looking at the hdf5-gfortran derivation, I see that it does contain the module in question:

nix repl
nix-repl> :l <nixpkgs>
nix-repl> hdf5-fortran.dev.outPath
"/nix/store/z1cpswhlldgj23d4fk0y34dk5g5qg1vk-hdf5-1.10.6-dev"
% ls /nix/store/z1cpswhlldgj23d4fk0y34dk5g5qg1vk-hdf5-1.10.6-dev/include/hdf5.*
/nix/store/z1cpswhlldgj23d4fk0y34dk5g5qg1vk-hdf5-1.10.6-dev/include/hdf5.h
/nix/store/z1cpswhlldgj23d4fk0y34dk5g5qg1vk-hdf5-1.10.6-dev/include/hdf5.mod

Adding this path solves the compilation error:

gfortran -I /nix/store/z1cpswhlldgj23d4fk0y34dk5g5qg1vk-hdf5-1.10.6-dev/include  test_hdf5.f90
[no error]

However I would have expected the gfortran wrapper to add this “-I” flag automatically, but it does not. Is this a bug?

Could you post your shell.nix? That would make it easier to figure out where the nix-shell when wrong.

I didn’t use a shell.nix file, I merely run nix-shell -p hdf5-fortran gfortran.

This package makes use of the library you mentioned: https://github.com/tviti/NCL.nix/blob/260b59af88807ab13f4c914ff379a17f3fd73040/default.nix and seems to create it’s own configuration thing. Perhaps you could do something similar to https://github.com/tviti/NCL.nix/blob/260b59af88807ab13f4c914ff379a17f3fd73040/default.nix#L63-L64 with an environment variable in a shell.nix.

I think you’re going to have to create some sort of an environment with a shell.nix and write a Makefile that uses that environment to call gfortran with the -I arguments

Thanks for the suggestion. I can patch the Makefile to include that directory, but I’m surprised that the gfortran wrapper does not do it automatically?

As far as I can tell, gfortran has no wrapper. Perhaps this is motivation to create a PR that adds a wrapper to gfortran.

2 Likes

I whipped up a minimal example for that if you’re still looking for a solution:

Should work both with nix-build and nix-shell.

2 Likes