18.3 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.

Some of the BLAS and LAPACK subroutines have been downloaded to the class account. The files are located in /usr/class/me390/src/. The routines have been compiled and collected into a library file called libmy_lib.a stored in /usr/class/me390/lib/libmy_lib.a.

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