Install Gfortran or Flang compiler on macOS Homebrew
Homebrew can install Fortran compilers including GCC and LLVM Flang.
Gfortran
Gfortran comes with GCC Homebrew package:
brew install gcc
As a complete C / C++ / Fortran compiler package, Gfortran doesn’t require additional flags or environment variables.
To use GCC compilers, source a script like:
p=$(brew --prefix gcc)/bin
v=14
export CC=$p/gcc-$v CXX=$p/g++-$v FC=$p/gfortran-$v
# to avoid GCC include errors -- MacOSX15.sdk incompatable at the moment with Homebrew GCC
export SDKROOT=/Library/Developer/CommandLineTools/SDKs/MacOSX14.sdk/
where v=14
is the major version number of the GCC compiler installed.
The SDKROOT line may be necessary when Homebrew GCC package hasn’t yet enabled the latest SDK–adjust to suite the system.
LLVM Flang
LLVM Flang is a separate package from the LLVM C/C++ compilers:
brew install flang
To use Flang compiler (works with Clang, AppleClang, GCC C-C++ compilers), source a script like:
export FC=$(brew --prefix flang)/bin/flang-new
To use LLVM Clang with Flang, source a script like:
p=$(brew --prefix llvm)/bin
export CC=$p/clang CXX=$p/clang++
export FC=$(brew --prefix flang)/bin/flang-new
Troubleshooting
When a new compiler version or macOS version or Xcode SDK is released, it may be necessary to adjust the environment variables or flags temporarily until Homebrew updates the package.
Some examples to try if needed:
-
path to libSystem.tbd and libc++.tbd
export LIBRARY_PATH=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib
-
path to the C++ standard library
export LDFLAGS=-lc++