Using libraries under Unix

A Fortran package of subprograms may contain hundreds of files. It is very slow and inconvenient to recompile these files every time you want to use any of the subroutines. Under the Unix operating system you can avoid this by making a library file. The library file is an object file, so you only have to compile your additional main (driver) program and then link it with library. (Linking is much faster than compiling.)

Libraries have file names starting with lib and ending in .a. Some libraries have already been installed by your system administrator, usually in the directories /usr/lib and /usr/local/lib. For example, the BLAS library may be stored in the file /usr/local/lib/libblas.a. You use the -l option to link it together with your main program, e.g.

      f77 main.f -lblas
You can link several files with several libraries at the same time if you wish:
      f77 main.f mysub.f -llapack -lblas 
The order you list the libraries is significant. In the example above -llapack should be listed before -lblas since LAPACK calls BLAS routines.

If you want to create your own library, you can do so by compiling the source code to object code and then collecting all the object files into one library file. This example generates a library called my_lib:

       f77 -c *.f
       ar rcv libmy_lib.a *.o
       ranlib libmy_lib.a 
       rm *.o
Check the manual pages or a Unix book for more information on the commands ar and ranlib. If you have the library file in the current directory, you can link with it as follows:
       f77 main.f -L. -lmy_lib
One advantage of libraries is that you only compile them once but you can use them many times.


[Fortran Tutorial Home]
boman@sccm.stanford.edu