PHYS 580 COMPUTATIONAL PHYSICS SPRING 2005
How to compile Fortran programs
NEW! Makefile (go to bottom of page)
You start with a source file containing a Fortran code, say, test. f. Now compile:
f77 -c test.f
will produce an object file test.o. The "-c" is a flag that tells the compiler to only compile and not to link into an executable.
f77 -o test.x test.o
will generate an executable file test.x. (The flag "-o" tells the compiler that the string following is to be the name of the executable.) The process of generating an executable from a object file, or from multiple object files, is known as linking. The .x suffix is not required; you can name it anything:
f77 -o Bob test.o
will produce Bob as an executable file. To execute, simply type the name
(this is necessary if you have not set up the path correctly)
You can also combine compiling and linking into one step:
f77 -o test.x test.f
which will also produce test.o as an intermediate step.
It is often convenient to break up your program into multiple source files. This allows you to easily reuse useful subroutines, such as those for integration and eigenvalues.
You can compile each source file separately and link together at the end
f77 -c mainprogram.f
f77 -c eiglib.f
f77 -c integratelib.f
which produce object files mainprogram.o, eiglib.o, and integratelib.o. These are linked
f77 -o bigprogram.x mainprogram.o eiglib.o integratelib.o
You can also combine all these steps together:
f77 -o bigprogram.x mainprogram.f eiglib.f integratelib.f
However, if you have many source files and are developing and editing only one, it is faster and more convenient to just recompile the one file and to link all the files together. This process can be automated using the make utility, which draws upon the makefile (more about this later).
There are other flags which are useful, the most important of which is the -O flag which means to optimize. This can make significant difference in speed, at least in Fortran code. Other flags tend to be compiler specific.
One common mistake is to go out of the declared dimension of the array. You can use a compiler flag to check for this (although it turns off optimization and should be only used for validation and debugging, not for useful runs). Here is a sample program that goes out of bounds.
For the GNU f77 (or g77) compiler the flag is -fbounds-check
f77 -o tb.x -fbounds-check testbounds.f
For the Intel ifc (or ifort) compiler the flag is -CB
ifc -o tb.x -CB testbounds.f
A link to reasonable tutorial to makefiles (for C++ programs but the grammar is the same)
You can get here a basic "makefile". It must be saved as "makefile"or "Makefile"
Also a more advanced and flexible (but less transparent) version of a makefile