Compiling Multiple Files in Liux using make

There are generally three distinct steps in compiling some code to and executable. They are:
  1.  Compiling the code to Assemble code
  2. Assembling the Assembly code to object code
  3. linking the object code together into an executable
Example: Consider a project which contains three c programs for e.g. pc1.c pc2.c & pc3.c and a header file test.h which is used in pc2.c . Let the definition of the programs be
int main()
      printf("program 1\n");
      return 0;
void pc2_test()
      int i=max;// max is defined in test.h
      printf("%d: value copied from header file\n",i);
      printf("program 2\n");
void pc3_test()
      printf("program 3\n");
#define max 3
make utility:
make is a system designed to create programs from large source code trees and to maximize the efficiency of doing so. To that effect, make uses a file in each directory called Makefile . This file contains instructions for make on how to build your program and when.
There are three important parts to a Makefile:  the dependency line and the command line and macro line
Step1: Open a file named makefile
>vim makefile
Step1: Defining the dependency line 
fun: pc1.o pc2.o pc3.o                          
Here pc1.o pc2.o pc3.o are the object file for the respective *.c files which defines the project
and fun is the project name
defining the dependencies of pc1.o
pc1.o: pc1.c           
which means main.o is dependent on main.c
if the program is dependent on a external header file
i.e. for the case of pc2.c
pc2.o: pc2.c test.h
Step2: defining the command lines
for the object file to be created the *.c file has to be compiled
 for the  project defnition line 
          gcc -c fun main pc1.o pc2.o pc3.o
compilation line for creating pc1.o etc
           gcc -c pc1.o
The complete program can be sumarized as 
fun: pc1.o pc2.o pc3.o 
      gcc -c fun main pc1.o pc2.o pc3.o
pc1.o: pc1.c   
      gcc -c pc1.c
pc2.o: pc2.c test.h   
      gcc -c pc2.c
pc3.o: pc3.c   
      gcc -c pc3.c

Step4: To run the makefile
go to the terminal
type make
and to complile the programs
run ./fun  here fun is the project name specified

AjSmart Tehnology geek

Sole blogger :(

1 comment: