Link Library in Unix/Linux

A link library contains precompiled object code. During linking, the linker uses the link library to complete the linking process. In Linux, there are two kinds of link libraries; static link library for static linking, and dynamic link library for dynamic linking. In this section, we show how to create and use link libraries in Linux.

Assume that we have a function

// musum.c file

int mysum(int x, int y){ return x + y; }

We would like to create a link library containing the object code of the mysum() function, which can be called from different C programs, e.g.

// t.c file

int main()

{

int sum = mysum(123,456);

}

1. Static Link Library

The following steps show how to create and use a static link library.

  1. gcc -c mysum.c                      # compile mysum.c into mysum.o
  2. ar rcs libmylib.a mysum.o      # create static link library with member mysum.o
  3. gcc -static c -L. -lmylib           # static compile-link t.c with libmylib.a as link library
  4. a. out # run a.out as usual

In the compile-link step (4), -L. specifies the library path (current directory), and -l specifies the library. Note that the library (mylib) is specified without the prefex lib, as well as the suffix .a

2. Dynamic Link Library

The following steps show how to create and use a dynamic link library.

(1). gcc –c -fPIC mysum.c               # compile to Position Independent Code mysum.o
(2). gcc
shared -o libmylib.so mysum.o # create shared libmylib.so with mysum.o
(3). gcc t.c -L. –lmylib                # generate a.out using shared library libmylib.so
(4).
export LD_LIBRARY_PATH=./          # to run a.out, must export LD_LIBRARY=./
(5). a.out                              # run a.out. ld will load libmylib.so

In both cases, if the library is not in the current directory, simply change the -L. option and set the LD_LIBRARY_PATH to point to the directory containing the library. Alternatively, the user may also place the library in a standard lib directory, e.g. /lib or /usr/lib and run ldconfig to configure the dynamic link library path. The reader may consult Linux ldconfig (man 8) for details.

Source: Wang K.C. (2018), Systems Programming in Unix/Linux, Springer; 1st ed. 2018 edition.

Leave a Reply

Your email address will not be published. Required fields are marked *