User defined functions in C language:
- As you know, there are 2 types of functions in C. They are, library functions and user defined functions.
- Library functions are inbuilt functions which are available in common place called C library. Where as, User defined functions are the functions which are written by us for our own requirement.
Adding user defined functions in C library:
- Do you know that we can add our own user defined functions in C library?
- Yes. It is possible to add, delete, modify and access our own user defined function to or from C library.
- The advantage of adding user defined function in C library is, this function will be available for all C programs once added to the C library.
- We can use this function in any C program as we use other C library functions.
- In latest version of GCC compilers, compilation time can be saved since these functions are available in library in the compiled form.
- Normal header files are saved as ”file_name.h” in which all library functions are available. These header files contain source code and this source code is added in main C program file where we add this header file using “#include <file_name.h>” command.
- Where as, precompiled version of header files are saved as “file_name.gch”.
Steps for adding our own functions in C library:
Step 1:
For example, below is a sample function that is going to be added in the C library. Write the below function in a file and save it as “addition.c”
addition(int i, int j)
{
int total;
total = i + j;
return total;
}
{
int total;
total = i + j;
return total;
}
Step 2:
Compile “addition.c” file by using Alt + F9 keys.
step 3:
addition.obj file would be created which is the compiled form of addition.c file.
Step 4:
Use the below command to add this function to library.
c:\> tlib math.lib + c:\ addition.obj
+ means adding c:\addition.obj file in the math library.
We can delete this file using – (minus).
c:\> tlib math.lib + c:\ addition.obj
+ means adding c:\addition.obj file in the math library.
We can delete this file using – (minus).
Step 5:
Create a file “addition.h” & declare prototype of addition() function like below.
int addition (int i, int j);
Now addition.h file containing prototype of function “addition”.
int addition (int i, int j);
Now addition.h file containing prototype of function “addition”.
Step 6:
Let us see how to use our newly added library function in a C program.
Output:
Total = 30
|
No comments:
Post a Comment