No contributions and responses
.Looks like no one has liked this thread.
Compilation or linking of mutiple files to a single file
Another advantage of running c in linux is compliation or linking of multiple c files into a single file.Here multiple files means not multiple programs but the files which contains the part or functions of the main program.
consider the following C program
Code:
#include<stdio.h>
int main()
{
void func1(void);
void func2(void);
printf("Main function start\n");
func1();
func2();
printf("Main function end\n");
}
void func1()
{
printf("First function\n");
}
void func2()
{
printf("Second function\n");
}
When you run this program, the output will be
Code:
Main function start
First function
Second function
Main function end
With linux, there is no restriction that the functions func1 and func2 must be written in the same file itself.
i.e,.
save this as func.c
Code:
#include<stdio.h>
int main()
{
void func1(void);
void func2(void);
printf("Main function start\n");
func1();
func2();
printf("Main function end\n");
}
this as func1.c
Code:
void func1()
{
printf("First function\n");
}
and finally this as func2.c
Code:
void func2()
{
printf("Second function\n");
}
Now as u can see the above program is split into 3 parts.one the main program and the remaining 2 functions.
now in order to compile the above 3 programs as a single file you have to issue command
Code:
bash-2.05b$ cc -o output.out func.c func1.c func2.c
In general the syntax is
Code:
cc -o <outputfilename> <input files>
Also, if you want to give your executable file a different name than a.out, use
Code:
cc -o <output file> <source file>
The 3 files will be compiled as one.Now to run the program type
./output.out.The same output you will get as given above
You can divide the main program only at the points of the end of the function.That means u cannot split the program as
Code:
#include<stdio.h>
int main()
{
void func1(void);
void func2(void);
printf("Main function start\n");
func1();
func2();
and
Code:
printf("Main function ends\n");
}
Some of the uses of linking are:
1.Improves redability of the main program
2.file containing the function can be used by other programs.That means once you create a separate file for a function,u can reuse it if other program requires the function.all you have do it is specify the function declaration in the main program and link this function during compilation.
3.makes the main program look small and hence debugging is easy.