A Developer's Diary

May 4, 2011

Static Library - An Introduction

Static library is a group of object files bundled together in an archive by the archiver program. The static libraries have a .a extension.

Advantages
1. The executable is not dependent on any library as the library code is included in the binary
2. In some cases performance improvement
Command for creating a static library
ar rcs -o libmylibrary.a file1.o file2.o file3.o

Steps for generating the static library libemployee.a for the Employee Program written in the previous post

1. Compiling source files to object files
g++ -Wall -c -fPIC -O -I. -o Employee.o Employee.cpp
2. Command for building the archive file libemployee.a
ar -rcs -o libemployee.a Employee.o

The Client Program
 1 #include "Employee.h"
 2 #include <iostream>
 3 
 4 int main()
 5 {
 6     Employee *emp = new Employee("Pankaj", 26);
 7     std::cout << "Employee Name: " << emp->getName() << std::endl;
 8     std::cout << "Employee Age : " << emp->getAge() << std::endl;
 9     delete emp;
10     return 0;
11 }

Compiling the Client Program
g++ -Wall -c -fPIC -O -I. -o rClient.o Client.cpp

Linking the client executable with the static library
gcc -o client Client.o -fPIC -Wl,-rpath,. -L. -lstdc++ -lemployee

Running ldd against the client executable gives us the following result:
$ ldd ./client 
 linux-vdso.so.1 =>  (0x00007fff7cde3000)
 libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00007fb85d978000)
 libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fb85d762000)
 libc.so.6 => /lib64/libc.so.6 (0x00007fb85d3f5000)
 libm.so.6 => /lib64/libm.so.6 (0x00007fb85d19e000)
 /lib64/ld-linux-x86-64.so.2 (0x00007fb85dc81000)

The client executable is not dependent on the employee library

1 comment :

Thomas John said...

Hello,

I am Thomas John, representing the website Ubuntu Manual. As the name suggests UM is a site that delivers content related to Ubuntu, its derivatives and related software. We are looking to expand our website and are seeking talented writers familiar with Ubuntu or Linux or similar open source software to include in our community of writers.

We had come across your article on the web and was wondering whether you would be interested in writing for us. We can provide sufficient compensation for your writings and would love to have you as one of our writers.

I will provide you with the rest of the details if you are interested.

Cheers,
--
Thomas John,
Ubuntu Manual

Post a Comment