Adding Functions to Library in C

This might be known to many but  I recently tried it and got it working.

Suppose you make a function in C(for example here we take a simple function which calculates the square of a number).

Its a fairly simple one and I want to add in in a library thus making its reuse possible.

(Please note I am taking a very simple scenario because the actual program is not the point of focus here, but the procedure is)

The function:

int square(int n)

{

return n*n;

}

Compile the file:

Compile the file in which you have written this function. Lets call it “sqr.c”. A new file called “sqr.obj” is created contained compiled code.

Add the function to Library:

Add the function to the library “maths.lib” using the following command.

C:\>tlib maths.lib + c:\sqr.obj

Please note the paths. Your paths may be different than mine!

here, maths.lib is the library and + is a switch which indicates that we want to add a new function to the library and the object file is at the given path.

Header file:

Add the prototype of square() function in a header file (lets say “square.h”) This file should be included in the program where we want to use the function. we can use it as:

#include “c:\square.h”

Thats all !

Use the function and enjoy !!

Hope it helps.