C Programming language

adplus-dvertising
Adding function to library in C
Previous Home Next

Adding function to the library

We can add user-defined functions to the library. It makes sense in doing so as the functions that are to be added to the library are first compiled and then added. When we use these functions (by calling them) we save on their compilation time as they are available in the library in the compiled form.

compilers provide a utility called ‘tlib.exe’ (Turbo Librarian). Let us use this utility to add a function factorial( ) to the library.

Given below are the steps to do so:

  1. Write the function definition of factorial( ) in some file, say fact.c’.
    int factorial ( int num )
    {
    int i, f = 1 ;
    for ( i = 1 ; i <= num ; i++ )
    f = f * i ;
    return ( f ) ;
    }
    
  2. Compile the ‘fact.c’ file using Alt F9. A new file called ‘fact.obj’ would get created containing the compiled code in machine language. (c) Add the function to the library by issuing the command
    C:\>tlib math.lib + c:\fact.obj
    
    Here, ‘math.lib’ is a library filename, + is a switch, which means we want to add new function to library and ‘c:\fact.obj’ is the path of the ‘.obj’ file.
  3. Declare the prototype of the factorial( ) function in the header file, say ‘fact.h’. This file should be included while calling the function.
  4. To use the function present inside the library, create a program as shown below:
    #include "c:\\fact.h"
    main( )
    {
    int f ;
    f = factorial ( 5 ) ;
    printf ( "%d", f ) ;
    }
    
  5. Compile and execute the program using Ctrl F9.
Previous Home Next