Suppose you have a C program whose main function is in mainc
Suppose you have a C program whose main function is in main.c and has other functions in the files input.c and output.c:
o What command(s) would you use on your system to compile and link this program?
Solution
Please follow the code and data for description :
Compilation :
In the stream of Computer Science the term compilation refers to the processing of source code files that may be either .c, .cc, .cpp and the creation of an respective \'object\' file. This file doesn\'t create anything that the user can actually run but the compiler produces the machine language instructions that corresponds to the source code file that was compiled for the ease of computer interaction and understanding.
For the given example, if we compile three separate files and to be noted that we don\'t link them then, we will have three seperate object files created as an output, each with the name <filename>.o or <filename>.obj. Each of these files contains a translation of the corresponding source code file transferred into a machine language file. As these cannot be run as it is we need to turn them into executable files so tht the operating system can use them. That\'s where the linker comes in.
Linking :
And now the process of linking refers to the creation of a single executable file from multiple object files. In this step, during compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren\'t mentioned.
Now moving on to the current scenario of three functional file namely the main.c, input.c, output.c which might be dependent need to be compiled and linked together for the program to run hassle-free.
So to do we first need to convert the files to the respective object files called as the compilation and then needs to be linked for the execution of the code. This can be done in a single line or could be seperated for the clear and perfect execution. This could be seen below :
a)
In general these process of the compilation and linking basically depend on the type of the compiler the user is using, but for instance assuming you are using gcc, you could use something like this:
gcc -o program main.c input.c input.c
Here the -o converts the source to the object and then gives the ease for the executable files to be run against the OS and that produces the output taking the three files as the reference.
If this would be puzzling the process could be done in another way even,
b)
We can also compile each file to the respective object code separately and then link the object files together for the execution :
gcc -c main.c
gcc -c input.c
gcc -c output.c
gcc -o program main.o input.o output.o
Hope this is helpful.
