Makefile
Makefile
Makefile
Objectives
z Header Files.
//fact.h
#include<stdio.h>
int factorial(int);
//fact.c //main.c
#include "fact.h" #include "fact.h"
1
In the above example, we write two lines in the header fact.h
#include<stdio.h> //include the a standard c header file stdio.h
int factorial(int) //gives the prototype of a subroutine factorial.
When we use #include "fact.h", main.c knows “factorial “ is a subroutine which has an
integer as its argument and returns an integer.
The first and second line will generate two object files factorial.o and main.o.
The last line will link them to generate an executable main.
http://www.gnu.org/software/make/manual/make.html
2
Example 3. The Example Makefile
makefile
#comment: 1. makefile example
clean:
rm -rf *.o main
Using Make to generate executable: make (using makefile as the default input) or
make –f filename (using filename as the input)
A shell line
A rule: One makefile is composed of several rules, it tells Make when and how to make a file.
A dependency line(prerequisite): it tells Make which files the target depends on.
A shell line: it tells Make how to build a target.
3
fact.c fact.h main.c
fact.o main.o
main
For example
main: fact.o main.o
tells us main depends on two files fact.o and main.o, if fact.o or main.o is newer than main or
main does not exist. Make will run the shell line
gcc -o main fact.o main.o
to generate the executable main.
The Make Process is Recursive! For example, if we change main.c and type make, we will see
the following line is executed(Note the above graph)
gcc -c main.c
gcc -o main fact.o main.o
question: 1. If you change fact.h and type make, what will happen?
2. Type “make clean”, what will happen?
Additional dependencies: From the above graph, we see both fact.c and main.c depend on fact.h,
we can use a new line to list this relation:
4
mk1
main: fact.o main.o
gcc -o main fact.o main.o
fact.o: fact.c
gcc -c fact.c
main.o: main.c
gcc -c main.c
clean:
rm -rf *.o main
main: $(OBJS)
$(LD) -o main $(OBJS)
fact.o:fact.c
$(CC) -c fact.c
main.o: main.c
$(CC) -c main.c
$(OBJS) : fact.h
clean:
rm -rf *.o main
5
We can print out the values for the predefined variables by using
$(OBJS) : fact.h
clean:
rm -rf *.o main
How it works:
6
See http://www.gnu.org/software/make/manual/make.html#Automatic-Variables for the means of
$<, $@.
Therefore,
$(OBJS) : %.o : %.c
$(CC) -c $< -o $@
is equavilent to two rules
fact.o: fact.c
$(CC) –c fact.c -o fact.o
main.o: main.c
$(CC) –c main.c -o main.o