A makefile consists of a set of rules. A rule consists of 3 parts: a target, a list of pre-requisites and a command, as follows:
target: pre-req-1 pre-req-2 … command
Simple Makefile
the makefile can be named “makefile”, “Makefile” or “GNUMakefile”, without file extension
all: hello.exe
hello.exe: hello.o
gcc hello.o -o hello.exe
hello.o: hello.c
gcc -c hello.c
clean:
rm hello.o hello.exe
this makefile builds hello.c into hello.exe
- In the above example, the rule “
all” has a pre-requisite “hello.exe”.makecannot find the file “hello.exe”, so it looks for a rule to create it. The rule “hello.exe” has a pre-requisite “hello.o”. Again, it does not exist, somakelooks for a rule to create it. The rule “hello.o” has a pre-requisite “hello.c”.makechecks that “hello.c” exists and it is newer than the target (which does not exist). It runs the command “gcc -c hello.c”. The rule “hello.exe” then run its command “gcc -o hello.exe hello.o”. Finally, the rule “all” does nothing
// hello.c
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}Running Makefile
have both makefile and hello.c under the same directory
to build, execute the make command
> ls
hello.c makefile
> make
gcc -c hello.c
gcc -o hello.exe hello.o
> ls
hello.c hello.o hello.exe makefile
to undo build, run the following command
> make clean
hello.c makefile