Installing Fortran Compiler on Ubuntu
The most widely used Fortran compiler for Ubuntu is gfortran (part of the GNU Compiler Collection), which is open-source and well-supported. To install it:
sudo apt update
sudo apt install gfortran
gfortran --version
For users needing a specific gfortran version (e.g., 7.x), add the Ubuntu Toolchain PPA, update the package list, and install the desired version:
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt update
sudo apt install gfortran-7
Switch between installed versions using update-alternatives:
sudo update-alternatives --config gfortran
Follow the prompts to select your preferred default version.
Writing and Compiling Fortran Programs
Create a Fortran source file (e.g., hello.f90) using a text editor (nano, vim, or gedit):
nano hello.f90
Add a simple “Hello, World!” program:
program hello
implicit none
print *, 'Hello, World!'
end program hello
Save and exit the editor. Compile the program with gfortran:
gfortran -o hello hello.f90
Run the executable:
./hello
This will output `Hello, World!’ to the terminal.
Key Libraries for Scientific Computing
Scientific computing in Fortran relies on optimized libraries for numerical operations. Essential libraries include:
sudo apt install libblas-dev
sudo apt install liblapack-dev
sudo apt install libfftw3-dev
sudo apt install libmkl-dev
Link these libraries during compilation (e.g., for LAPACK):
gfortran -o my_program my_program.f90 -llapack -lblas
.
Enabling High Performance with Parallelism
For large-scale scientific computations, parallelism is critical. Two primary approaches are:
!$omp parallel do) and compile with:gfortran -fopenmp -o parallel_program parallel_program.f90
sudo apt install libopenmpi-dev openmpi-bin
mpif90 -o mpi_program mpi_program.f90
mpirun -np 4 ./mpi_program # Run with 4 processes
These tools allow you to leverage multi-core CPUs and clusters for faster execution.
Recommended IDEs for Fortran Development
While text editors suffice for basic coding, IDEs enhance productivity with features like syntax highlighting, debugging, and project management:
Best Practices for Fortran Development
To write efficient, maintainable Fortran code:
-O2 or -O3 for advanced optimizations and -march=native to tailor code to your CPU architecture:gfortran -O3 -march=native -o optimized_program optimized_program.f90
gprof (for profiling) or perf (for hardware-level analysis) to identify bottlenecks:gfortran -pg -o profiled_program profiled_program.f90
./profiled_program
gprof profiled_program gmon.out > analysis.txt
implicit none to prevent undeclared variables, allocatable arrays for dynamic memory, and modules for code organization.