Compiling and linking a library

Compiling a static library

To compile a static library:

  1. Compile each source file into an object file, with no linking.
  2. Use the GCC ar command to add the generated object files to an archive library file.

For example:

xlc -c bar.c example.c
ar -rv libfoo.a bar.o example.o 

Compiling a shared library

To compile a shared library:

  1. Compile your source files into an object file, with no linking. For example:
    xlc -c foo.c
     
    
  2. Use the -qmkshrobj compiler option to create a shared object from the generated object files. For example:
    xlc -qmkshrobj -o libfoo.so foo.o
     
    

Linking a library to an application

You can use the same command string to link a static or shared library to your main program. For example:

xlc -o myprogram main.c -Ldirectory -lfoo

where directory is the path to the directory containing the library.

By using the -l option, you instruct the linker to search in the directory specified via the -L option for libfoo.so; if it is not found, the linker searches for libfoo.a. For additional linkage options, including options that modify the default behavior, see the GCC ld documentation.

Linking a shared library to another shared library

Just as you link modules into an application, you can create dependencies between shared libraries by linking them together. For example:

xlc -qmkshrobj -o mylib.so myfile.o -Ldirectory -lfoo
 
IBM Copyright 2003