Monday, February 18, 2013

Writing and using libraries

Basically libraries mean collection of files that are reused to reduce the size of main program. Every program even simple hello program uses libraries. For example if your program has GUI, it will be linked against windowing libraries.

 

Libraries can be static or dynamic, if we choose to use static library, size of the program will increases and difficult to upgrade, but easy to deploy. If we choose dynamic libraries then program size becomes reduced and easy to upgrade but difficult to deploy.


Archives(Static library):-

An archive is collection of object files stored as single file. When we provide an archive to the linker, the linker searches the archives for the object files which is required, linker extract them and links them into program. Archives files traditionally uses a .a extension rather than .o extension used by ordinary object file. The ar indicates archive and cr flag tells to create archive.

We can manually create archive by command shown below:


    $ar cr archivename.extension


When the linker encounters an archive on the command line, it searches the archive for all definitions of symbols (functions or variables) that are referenced from the object files that it has already processed but not yet defined. The object files that define those symbols are extracted from the archive and included in the final executable. Because the linker searches the archive when it is encountered on the command line, it usually makes sense to put archives at the end of the command line. For example lib.c contains code for function display and hello.c contains code defined by user.


Lib.c

display()

{

printf(”HELLO”);

}


hello.c


int main()

{

display();

return 0;

}


Shared libraries:-


A shared library also known as shared object or dynamically linked library. It is similar to a archive in that it is a grouping of object files. However there are many important differences. The most basic difference is that when a shared library is linked into a program, the final executable does not actually contain the code that is present in the shared library. Instead executable file contain only references to the shared library. If several programs on the system are linked against the same shared library, they will all reference the library, but none will actually be included. Thus, the library is “shared” among all the programs that link with it.


Second important difference is that shared library is not collection of object files, out of which the linker chooses those that are needed, satisfies undefined references. Instead, the object files that compose the shared library are combined into a single object file so that a program that links against a shared library always includes all of the code in the library, rather than just those portions that are needed.

No comments:

Post a Comment