Friday, November 10, 2006

Static libraries in linux

Some days back I was trying to create static libraries in linux. I tried to search for the method,but did not find anything anywhere.I got the method from a teacher,and it worked.So here it is for anyone who does not know.....
1.Create files having the impelementations of the functions you wish to have in the library.Suppose we write test1.c and test2.c.So,test1.c is
#include
int square(int a)
{
return(a*a);
}
and test2.c is
#include
int cube(int b)
{
return(b*b*b);
}
2.compile them as
gcc -c test1.c test2.c
3.write the header file having the prototypes of the functions.So,test.h is
int square(int);
int cube(int);
4.Write a program to test the library.Say it is program.c
#include
#include "test.h" //assuming it is in the same directory
int main()
{
int num;
printf("Enter a number\n");
scanf("%d",&num);
printf("Square=%d\nCube=%d\n",square(num),cube(num));
return(EXIT_SUCCESS);
}
5.Compile the program as
gcc -c program.c
then link with the other object files
gcc -o program program.o test1.o test2.o
6.Run it as
./program
7.Create a library from the individual object files
ar crv libtest.a test1.o test2.o
note that this is a static library with extension .a
8.Now we need to list the library into the system list,for this,do
ranlib libtest.a
9.This library can be linked with programs in a number of ways....
gcc -o program program.c libtest.a
and then
./program
to run the program

Or,you can do
gcc program.c libtest.a
to compile and link and
./a.out
to run the program

Or,you can do
gcc -o program program.c -L. -ltest
and
./program
Here -L. instructs the compiler to search for libtest in the current directory.

Similarly,we also have
gcc program.c -L. -ltest
and
./a.out

We can also place the library in the /usr/include directory.Then we wont need the -L option to specify the path.But -ltest option is needed.

1 Comments:

At 9/18/2008 10:14 AM, Blogger sanjib_sur said...

eta amr kaje lege gelo...
thnxx abhishekda..

 

Post a Comment

<< Home

free web counter
free web counter