A simple fix to a common issue with Anaconda libgfortran on macOS

To compile some Fortran code that used features newer than Fortran 95, I switched the default gfortran from the conda one (version 4.8) to the latest GCC one (version 7.3). After that, I found that I could no longer execute some previously compiled Fortran programs and I also ran into troubles with some Anaconda Python packages. (Maybe it was my fault not to statically link them.) I got the same error for all of them:

dyld: Library not loaded: @rpath/./libgfortran.3.dylib

I searched it and there were quite a few people who ran into the same error message with the gfortran in Anaconda Python Distribution. However, discussions on the GitHub issues page were not always helpful. I tried some possible solutions, including the simpleminded “uninstall and reinstall” way, but none of them helped. Well, lucky for me that a solution appeared after flipping through three pages in the Google search results: https://github.com/conda-forge/libgfortran-feedstock/issues/1.

The fix is simple. Switch the default gfortran back to the Anaconda one. Check the path of DYLD_FALLBACK_LIBRARY_PATH. If it is empty, set it to the Anaconda lib directory, e.g., something like /Users/<your_name>/anaconda/lib. That’s it. You may want to add it to the .bash_profile because macOS seems to constantly clear it. (Though I suspect that there may be a more elegant solution, at the moment this solved my problem.)

I’m still not quite happy with the fact that conda on macOS is stuck at gfortran 4.8. That just means a lot of new features added in the Fortran 2008 standard cannot be used to build a portable Python package. Of course, there is another limitation that is f2py, which does not seem to support any feature added after Fortran 90 for the time being. In general, I feel that wrapping C code in Python is much more natural and robust than wrapping Fortran code.

(Wrote this while waiting for God of War 4 to be downloaded on my PS4 Pro. :D)