Facebook

How to use a function from one file into another file in C


So lets say there is some function which you need to use in many programs of your project. One way is to copy paste the code in each and every file. But this will increase the size of every file and what if there are thousands of file. I am sure you would not like it. Also C is the programming language which needs very less space and is used in application which require minimum space. So copying same code in every file seems not a viable option. 


Also what if one day you need to change the code a bit. Oh man ! You are doomed. Better go for a vacation and meanwhile your boss will give this editing task to someone else. 



What? you don't have a boss. Self employed. A passionate programmer. Great ! Then you must know this thing already.


So copying same code to every file have 2 major disadvantages.



  • Increase file size.
  • Editing the code is a herculean task.                                                    

So here we present you a very simple example of how to call and use a function, defined in other file, in your file.


We will keep this as simple as possible.

"Simplicity is beauty. "

1. Let say there is a file abc.c which contains a function. code of the file is given below.

 void display ( )  
 {    
   printf ("Welcome to Newbie42.blogspot.in \n");  
 }  

2. Now you want to use this function in many files and one of the file is prog.c

3. Now first create a header file. Give it any name. What about  funny.h?


4. Write the signature/declaration of your function in this header file.

 void display ( );  
5. Now write your code in prog.c file.
  
 #include "funny.h"  
   
 int main()  
 {    
   display();  
   return 0;  
 }  
6. Now compile both files together 
$ cc prog.c abc.c

7. Run the program

$ ./a.out

Working? Yes? Great.


This is the simplest example. This method will be very useful when function is very big and there are large number of files in which it will be used.


Now what is you are using many functions from many different files. In that case you need to compile all files together. What if you need to repeat the same task multiple times. Typing name of many files on command line terminal and then repeating it might be a tedious task. 

Although history command is very useful at that time. We will explain you how to create Makefile and compile multiple files in one go and many more things in next tutorial.






No comments:

Post a Comment