The best starting point in any exploration of gfortran might just be the GFortran Compiler Wiki. From there, you can find downloads for your desired operating system and general information on the whole project.
The gfortran compiler can run under almost any operating system. My preference is to run gfortran in a Linux environment and I have chosen to do this through the Windows Subsystem for Linux (WSL2) on my Windows 11 Pro laptop.
To install gfortran in this environment, run the following from the command prompt.
sudo apt install gfortran
Once installed, the gfortran version on your system can be determined using the command-line switch shown here.
gfortran --version
You can choose your own source code editing environment, but my own preference is to use VSCode as it works nicely under Windows and includes integration with the WSL2 environment.
Compiling a fortran listing (in this case, main.f90) into an object file is easy enough.
gfortran -c main.f90
This command will generate an object file, main.o. To create an executable, simply drop the -c switch.
The default target (when you don’t include -o switch) will be a.out. That’s fine for testing, but you probably want a name that makes sense for your application.
gfortran main.f90 // executable is a.out
gfortran main.f90 -o main // executable is main
./main
If you want to create an executable which includes a module, do the following (where module.f90 contains your module code).
gfortran module.f90 main.f90 -o main
File extensions (f90, f95, etc.) are important in gfortran. They are also used by coding tools like VSCode to control default behaviour and identify syntax. The samples above use the .f90 extension for Fortran 90.
It is also possible to use object files produced in the C language with your gfortran programs.
By default, the gcc compiler will prefix objects with a leading underscore. The gfortran compiler does not. It is also important to note that objects in Fortran are postfixed with an underscore, so our C functions must have the underscore added to the function name.
gcc -c -fno-leading-underscore mycsub.c
#include <stdio.h>
void csub_(char *str) {
printf("%s\n", str);
}
The object file produced in the example above could be used to expose the csub routine to a fortran program.
gfortran mycsub.o test.f90 -o test
! Listing for test.f90
PROGRAM MYPROG
CHARACTER(15) str
str = "the quick brown"
CALL csub(TRIM(str)//char(0))
END PROGRAM MYPROG
Notice that, in the fortran source, we call our c function without the trailing underscore character.
There are many good sources of information on mixed-language programming. An exploration of that is beyond the scope of this article, but know that there are a few complexities to consider for those wishing to make use of this capability.
This should get you started. Add your topics of interest in the comments section.
Updated: November 23, 2023
Leave a comment