Sunday, 28 July 2013

Creating your own library using GNU's archive (An interesting example for the ar command)

Hi ,

Follow this post if you want to start up with some basic information regarding C library .

In this post  you will be creating your own library and also be using it in your own program , the post will also demonstrate the use of the ar(archive) command.

Lets start Creating and using our library

STEP 1 :- Lets create two files for demonstration .

File 1 } myadd.c

#include<stdio.h>


int myadd(int a , int b)
{
int res;

res = a + b;

return res;
}


File 2 } mysub.c

#include<stdio.h>


int mysub(int a , int b)
{
int res;

res = a - b;

return res;
}


STEP 2 :- Lets create object codes of the above two c codes


 gcc -c myadd.c 


 gcc -c mysub.c 


Follow this post to get some more information about the above command.

STEP 3 :- Lets create our header file having the prototypes of the myadd() and mysub() functions.

myheader.h


#include<stdio.h>

int myadd(int a , int b);

int mysub(int a , int b);


STEP 4 :- Lets create the library file using the ar command .
We specify the name of the library file and the object codes to be grouped together as a library as the arguments to the ar command .



ar cr mylib.a myadd.o mysub.o

The GNU ar program creates, modifies, and extracts from archives.  An archive is a single file holding a collection of other files in a structure that makes it possible to retrieve the original individual files (called members of the archive). The option c creates the archive and the option r inserts the files into the archive by replacing any previouly existing members of the archive .

To view to contents of the mylib.a file we can use the following command

ar t mylib.a

STEP 5 :- Congrats you have created your library , Now lets write our own program with the library we created.

my_program_with_myheader.c

#include"myheader.h"

int main()
{
int res;
res = myadd(10 , 20);
res = mysub(50 , 20);

printf("The result after addition is %d\n",res);

printf("The result after subtraction is %d\n",res);
}

You can see the myheader.h file created by you being used in the program .

Lets compile the above file

gcc my_program_with_myheader.c mylib.a -o my_output

Now execute the output file to get the required output

./my_output

The below figure shows the whole process


























Thats it !!!

Leave your comments and suggestions and doubts in the comments sections

4 comments:

  1. This is cool! I will definitely try it!

    ReplyDelete
  2. please suggest a good book for ds?

    ReplyDelete
    Replies
    1. For detailed concepts you can refer this book

      Complete Reference Guide -Data Structures Through C
      by Agarwal , ajay

      but for easy understanding i would suggest

      balaguruswamy's book itself

      Delete