/* Ajith - Syntax Higlighter - End ----------------------------------------------- */

1.01.2010

Creating and using static libraries in Linux

Static libraries are simply a collection of ordinary object files.

For more information on shared libraries checkout - Creating and using shared libraries in Linux

Static libraries conventionally end with the ".a" suffix. Static libraries aren't used as often as they once were, because of the advantages of shared libraries. Still, they're sometimes created, they existed first historically, and they're simpler to explain.

Static libraries are often useful for developers if they wish to permit programmers to link to their library, but don't want to give the library source code (which is an advantage to the library vendor, but obviously not an advantage to the programmer trying to use the library). In theory, code in static ELF libraries that is linked into an executable should run slightly faster (by 1-5%) than a shared library or a dynamically loaded library, but in practice this rarely seems to be the case due to other confounding factors.


We use following source code files for this post.

calc_mean.c


double mean(double a, double b)
{
return (a+b) / 2;
}
calc_mean.h
double mean(double, double);
main.c - We are including our shared library in this application.
#include <stdio.h>
#include "calc_mean.h"

int main(int argc, char* argv[]) {

double v1, v2, m;
v1 = 5.2;
v2 = 7.9;

m  = mean(v1, v2);

printf("The mean of %3.2f and %3.2f is %3.2f\n", v1, v2, m);

return 0;
}
Creating the static library
First we have to create object file for calc_mean.c
gcc -c calc_mean.c -o calc_mean.o
Then, using archiver (ar) we produce a static library (named libmean.a) out of the object file calc_mean.o.
ar rcs libmean.a calc_mean.o
NOTE: A static library must start with the three letters 'lib' and have the suffix '.a'.

Compiling main program and linking with static library
gcc -static main.c -L. -lmean -o main
Now run the executable program 'main'
$./main

2 comments:

  1. hey it really worked..thanx for posting this...

    ReplyDelete
  2. its very good example thank u ...its really easy to understand ....................

    ReplyDelete

Your comments are moderated