Creating Libraries

Libraries are simply an indexed collection of object files that are included as needed in a linked program. Combining object files into a library makes it easy to distribute your code without disclosing the source. It also reduces the number of command-line entries needed to compile your project.

Static Libraries

Executables generated using static libraries are no different than executables generated from individual source or object files. Static libraries are not required at runtime, so you do not need to include them when you distribute your executable. At compile time, linking to a static library is generally faster than linking to individual source files.

To build a static library:

  1. Use the -fpic and -c option to generate object files from the source files: 
    ifort -fpic -c my_source1.f90 my_source2.f90 my_source3.f90

  2. Use the GNU ar tool to create the library file from the object files: 
    ar rc my_lib.a my_source1.o my_source2.o my_source3.o

  3. Compile and link your project with your new library: 
    ifort main.f90 my_lib.a

If your library file and source files are in different directories, use the -Ldir  option to indicate where your library is located:

ifort -L/for/libs main.f90 my_lib.a

Shared Libraries

Shared libraries, also referred to as dynamic libraries or Dynamic Shared Objects (DSO), are linked differently than static libraries. At compile time, the linker insures that all the necessary symbols are either linked into the executable, or can be linked at runtime from the shared library. Executables compiled from shared libraries are smaller, but the shared libraries must be included with the executable to function correctly. When multiple programs use the same shared library, only one copy of the library is required in memory.

To build a shared library:

  1. Use the -fpic and -c options to generate object files from the source files: 
    ifort -fpic -c my_source1.f90 my_source2.f90 my_source3.f90

  2. Use the -shared option to create the library file from the object files: 
    ifort -shared my_lib.so my_source1.o my_source2.o my_source3.o

  3. Compile and link your project with your new library:
    ifort main.f90 my_lib.so

See also Creating Shared Libraries.