April 11, 2014

How to add user defined function to library in C?

Hey Guys,
It may seem daunting at first but it is pretty much simple and am going to show you how to add a function to library in the gcc environment. I'll be using factorial as an example here.

Few things to remember,
  1. Library functions are precompiled programs to help save time while calling them
  2. You have to convert your function into a object file i.e factorial.o before saving them into the library
  3. After compilation, you can either link the library manually or link it via includes while executing. But here am going to show you how to do linking manually
Steps to be followed:
  • Create a user defined function which you want to add to library in the following format.
  • c3
  • go to cmd and change to the current folder where the program is stored.
  • Type gcc  -c  .\factorial.c . Here -c tells the compiler to convert the source code .c into an object code .oc4
  • c4
  • So you have converted the function into object file. Now it's time to add it to the library file which is usually someName.a
  • Type ar rvs  libsoe.a  .\factorialForLib.o c5
  • c5
  • In the above line, r means to replace objects in the library, The v option means verbose which tells you what is happening and when you use ar to make libraries of objects, use the s option.
  • Since we have added the function into the library , it is time for linking the library and using it in our calling program.
  • Type  gcc  .\factUsingLib.c  .\libsoe.a  -o  .\factUsingLibc6
  • c6
  • Now you would have successfully called a used defined library manually.

For more info click here

No comments:

Post a Comment