BudiBadu Logo
Samplebadu

Makefile by Example: Targets

GNU Make 4.x

A target is usually the name of a file that is generated by a program. This sample shows the basic syntax of a rule.

Code

# Basic syntax:
# target: dependencies
# 	 command

# Default target (first one)
all: hello

# Target 'hello' depends on 'main.o'
hello: main.o
	gcc -o hello main.o

# Target 'main.o' depends on 'main.c'
main.o: main.c
	gcc -c main.c

# Target 'clean' removes generated files
clean:
	rm -f hello main.o

Explanation

A Makefile consists of a set of rules. A rule generally looks like this: a target, followed by a colon and a list of dependencies (also called prerequisites), and then a series of commands on the following lines. The commands must be indented with a tab character, not spaces. This is a strict requirement in Makefiles that often trips up beginners.

The target is usually the name of a file that you want to generate (like an executable or an object file). When you run make target_name, Make checks if the target file exists and if it is up to date. A target is considered out of date if it doesn't exist or if any of its dependencies are newer than it.

If the target is out of date, Make executes the commands associated with the rule to update it. In this example, running make hello will first check if main.o needs to be updated. If main.c has changed, Make will recompile main.o before linking it to create the hello executable.

Code Breakdown

6
all: hello is a common convention. Since it's the first rule, running just make runs this target.
10
gcc ... The command MUST be preceded by a tab. Spaces will cause a "missing separator" error.