Featured Post

Trie implementation in C

How to create Static and Shared Libraries out of your source


Here is a simple method to create a static as well as shared or dynamic library in C.

There are two ways of creating libraries

1. Static Libraries

2. Shared or dynamic libraries


Difference between the two



Static Library
Shared Library
1. Static libraries are compiled into the program itself1. Shared libraries are compiled separately and referenced by the program
2. Program Size increases2. Program size is smaller but shared libraries are required at the runtime.
3. Every program has its own static library3. Shared library has only one copy and referenced by different programs

  Consider some files which we need to include in library

  1. logger.c*
  2. logger.h*
Process to create static library
  1. gcc -c logger.c -o logger.o 
  2. ar rcs liblogger.a logger.o
Process to create shared library
  1. gcc -c -fPIC logger.c -o logger.o 
  2. gcc -shared -Wl,-soname,liblogger.so.1 -o liblogger.so.1.0.1 logger.o
 Note:  lib is mandatory as the prefix to the library name.

Tar the source (if needed) using this command

     tar -zcvf liblogger.tar.gz liblogger/ 
where liblogger is the folder which contains all the source and library files.

 
Using test.c* as the test C file to use the library.


How to use static library :

Compile :gcc -static test.c -L. -llogger -o staticlog
Run : ./staticlog

How to use dynamic/shared library :

            Compile :gcc test.c -o dynamiclog -L. –llogger
            Run : ./dynamiclog


  We use llogger as the linker option since the the library name is liblogger

  So you must have understood how the things work !!

  * The source of these files is present at the link pointed by the file names.

Comments

  1. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.
    html5 audio player| html5 audio player

    ReplyDelete

Post a Comment

Please post your valuable suggestions