Static and Shared library

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 foo.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 -o foo.o

Creating Static library:
Static libraries are simply a collection of ordinary object files; conventionally, static libraries end with the ‘.a’‘ .
To generate object file use ‘-c‘ flag with gcc.

$ gcc -c bar.c -o bar.o

-c Compile or assemble the source files, but do not link. The compiler output is object files corresponding to each source file.
-o To specifiy the output file name.

A static library can contain more than one object files. We need to copy all object file in to a single file.
This single file is our static library. We can use archiver(ar) to create to create our static library.

$ ar rcs libbar.a bar.o

r – Insert the files into archive (with replacement).
c – Create the archive.
s – Write an object-file index into the archive, or update an existing one, even if no other change is made to the archive.

Static and Shared library

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s