software

Definition

Makefile

A Makefile is a file that stores shell commands to build a software project.

Purpose of Makefiles:

  • Split a complex build into sub-tasks
  • Give simple names to long, complex commands
  • Add flexibility (via variables)
  • Abstract recurrent patterns

Target

result: ingredients
	recipe 

Example:

hello: main.o hello.o
	gcc -o hello main.o hello.o # linking
 
main.o: main.c hello.h
	gcc -c -o main.o main.c # compiling
 
hello.o: hello.c hello.h
	gcc -c -o hello.o hello.c # compiling

Phony Target

Targets that do not correspond to actual files, only used to give a name to a rule.

.PHONY: all clean

all: supervisor generator

clean:
	rm -f *.o
	rm -f supervisor generator
.PHONY: all clean

all: supervisor generator

clean:
	rm -f *.o
	rm -f supervisor generator

buffer.o: buffer.c buffer.h
	gcc -std=c99 -pedantic -Wall -g -c buffer.c -o buffer.o

Patterns and Automatic Variables

Pattern rules specify recipes for a whole class of targets.
For instance: %.o for all object files.

  • We need special variables to retrieve target and dependency names in the recipe:
    • $@: target
    • $<: first dependency
    • : all dependencies
  • We can always add explicit dependencies (e.g., for .h files).
CC = gcc
CFLAGS = -std=c99 -Wall
 
hello: main.o hello.o
	$(CC) $(CFLAGS) -o $@ $ˆ
 
%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<
 
hello.o: hello.c hello.h
main.o: main.c hello.h

Examples

CC = gcc
FLAGS = -std=c99 -pedantic -Wall -D_DEFAULT_SOURCE -D_BSD_SOURCE -D_SVID_SOURCE -D_POSIX_C_SOURCE=200809L -g
 
.PHONY: all clean
 
all: supervisor generator
 
clean:
	rm -f *.o
	rm -f supervisor generator
 
buffer.o: buffer.c buffer.h
	$(CC) $(FLAGS) -c buffer.c -o buffer.o
 
graph.o: graph.c graph.h
	$(CC) $(FLAGS) -c graph.c -o graph.o
 
supervisor: supervisor.c graph.o buffer.o
	$(CC) $(FLAGS) supervisor.c graph.o buffer.o -o supervisor
 
generator: generator.c graph.o buffer.o
	$(CC) $(FLAGS) generator.c graph.o buffer.o -o generator
CC = gcc
DEFS = -D_BSD_SOURCE -D_SVID_SOURCE -D_POSIX_C_SOURCE=200809L
CFLAGS = -Wall -g -std=c99 -pedantic $(DEFS)
OBJECTS = main.o hello.o
 
.PHONY: all clean
all: hello
 
hello: $(OBJECTS)
	$(CC) -o $@ $ˆ
 
%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<
 
main.o: main.c hello.h
hello.o: hello.c hello.h
 
clean:
	rm -rf *.o hello