4. How to use Fortran on a Unix computer

Source code, object code, compiling, and linking

A Fortran program consists of plain text that follows certain rules (syntax). This is called the source code. You need to use an editor to write (edit) the source code. A commonly used editor in Unix is "vi".

When you have written a Fortran program, you should save it in a file that has the extension .f or .for. Before you can execute the program, you must translate it into machine readable form. This is done by a special program called a compiler. The Unix command which runs the FORTRAN 77 compiler is f77. The output from the compilation is named a.out by default, but you can choose another name if you wish. Once the program has successfully been compiled, and an executable file such as a.out has been created, you may run the program by simply typing the name of the executable file, for example a.out. (This explanation is a bit oversimplified. Really, the compiler translates source code into object code and the linker/loader makes this into an executable file.)

Examples:

Refer back to Section 3, and write the program file circle.f. Then compile and run the program.

If you need to have several executables at the same time, it is a good idea to give them (different!) descriptive names. This can be accomplished using the -o option. For example:

f77 -o circle circle.f

This will compile the file circle.f and save the executable in the file circle rather than the default a.out. Please note that object code and executables take a lot of disk space, so you should delete them when you are not using them. (The remove command in Unix is rm.)

Optional Topic

In the previous examples, we have not distinguished between compiling and linking. These are two different processes but the Fortran compiler performs them both, so the user usually does not need to know about it. In the next example we will use two source code files:

f77 -o circle circle1.f circle2.f

This will generate three files, the two object code files circle1.o and circle2.o, plus the executable file a.out. What really happened here, is that the Fortran compiler first compiled each of the source code files into object files (ending in .o) and then linked the two object files together into the executable circle. You can separate these two steps by using the -c option to tell the compiler to only compile the source files:

f77 -c circle1.f circle2.f
f77 -o circle circle1.o circle2.o

Compiling separate files like this may be useful if there are many files and only a few of them need to be recompiled. In Unix there is a useful command called make which is usually used to handle large software packages with many source files. These packages come with a Makefile and all the user has to do is to type make. Writing Makefiles is complete separate topic which we will not discuss further in this tutorial.

Copyright © 1995-7 by Stanford University. All rights reserved.

[ Index ]