How to create shared libraries with gcc?

gccShared libraries are libraries that are loaded by programs when they start. All programs that start afterwards automatically use the new shared library.

Code for the library:

This is the code that goes into the library. A function that calculate and return the factorial of a number.

fact.c

int
fact (int n)
{
        int fact  = 1;
        if(n == 0 || n == 1)
                return 1;
        while(n > 1) {
                fact = fact * n;
                n--;
        }
        return fact;
}

Now create a header file to define our function.

fact.h
int fact (int);

Creating Shared library:

First, create the object files that will go into the shared library using the gcc -fPIC or -fpic flag. The -fPIC and -fpic options enable “position independent code” generation, a requirement for shared libraries.

$ gcc -fPIC -Wall -g -c fact.c

Every shared library has a special name called the “soname”. The soname has the prefix “lib”, the name of the library, the phrase “.so”, followed by a period and a version number.

We can use ‘ld’, the GNU linker to create our shared library. The ld combines a number of object and archive files, relocates their data and ties up symbol references.

$ ld -shared -soname libfoo.so.1 -o libfoo.so.1.0 fact.o

Installing Shared library:

Once you’ve created a shared library, you’ll want to install it. The simple approach is simply to copy the library into one of the standard directories (e.g., /usr/lib) and run ldconfig(8).

Now copy the libfoo.so.1.0 to /usr/lib

$ sudo cp libfoo.so.1.0 /usr/lib/
$ sudo ldconfig -n /usr/lib/

Now create a symbolic link to our library.
$ sudo ln -sf /usr/lib/libfoo.so.1 /usr/lib/libfoo.so

Linking our Shared library:

This is the program that uses our ‘foo’ library.

main.c

#include <stdio.h>
#include "fact.h"
 
int
main(int argc, char *argv[])
{
        printf("%d\n", fact(4));
        return 0;
}

Compile:

$ gcc main.c -lfoo -o fact

Now run program:

$ ./fact
24

One Comment

Suvasish Mondal August 20, 2008

Thank you…this is what I was looking for two days…