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 libfoo.so.1 -o libfoo.so.1.0 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

Flags:
-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

Options:
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.