Monday 10 November 2014

Multifile programming

Q. What is multifile programming and why we use multifile programming concept?
Ans. First of all what is multifile programming.

You might have heard of your teacher saying "use multifile programming to do this assignment".

So multifile programming is to do the programming in a manner that its all functions become reusable by just including a file in the other programme. Easier to understand and modify.

Actually in multifile programming we write the functions declarations and definitions in two different files. Function declaration in .h file or any other extension except the reserved extension like .c /.cpp etc. And then we write the functions definition in the other file but different extension .c/.cpp. Then we make the object file of that c/cpp file using command gcc -c filename.c .

Do not forget to include .h file in you .c/.cpp file. Then we write the main file . In which we use the functions which we have declared in .h and defined in .c/.cpp file.

Here it goes the complete process
1. Make a header file including all functions declaration and you can declare the global variable also here but not the static variable, I will define the reason for this in future posts.
fun.h -> contains all the function declaration and may be global variable declarations

2. Make a .c/.cpp file fun.c which implements those functions written in fun.h. Remember to add the .h file in .c/.cpp file . Do not define main function in this fun.c file . Define only the functions which we have declared in fun.h. Then do no compile it as usual ways . 
                      Compile it like gcc -c fun.c.
Because it creates a object file not and executable file. Because it do no contain main function you can not compile it usual ways. Other wise it will give error main function is missing.

3. Make a main file mainfile.c/.cpp . Which does the task what we want to do using those functions.
Now while compiling this file do not remember to add the object file we made in the second step.
Ex.   gcc -o executable mainfile.c fun.o

-o rename the executable file as executable and we add the fun.o file to the mainfile so it does not miss any function definitions. 
Then run file as ./executable.

The reason why we are doing this because.
Suppose we want to give some developer information that they can use our functions but they can not see implementation. Then we can give him/her our header files containing function declaration and the object file. No need to give fun.c to anyone. No one will knows our implementation.

Another scenario is when we want to use those function in some other file include that header file and add that object file while compiling. 
I am sorry , I explained it only as linux user.

No comments:

Post a Comment

Related Posts

Related Posts Plugin for WordPress, Blogger...