Course contentsShow
← C
Lesson 819 of 1,21911. The Preprocessor and BuildFree lesson

Targets, dependencies, and recipes

Targets, dependencies, and recipes

What you'll learn: How to structure a Makefile by defining what to build, what is required to build it, and the specific commands needed to get the job done.

As your C projects grow, typing gcc main.c functions.c -o my_app every time you make a change becomes tedious. The make tool automates this using a simple rule-based system. Think of a Makefile like a kitchen recipe: you define the dish you want (the target), the ingredients you need (the dependencies), and the steps to cook it (the recipe).

The anatomy of a rule

Every instruction in a Makefile follows a specific three-part structure:

target: dependencies
	recipe
  1. Target: This is usually the name of the file you want to create (like an executable or an object file).
  2. Dependencies: These are the files that the target relies on. If any of these files change, make knows it needs to rebuild the target.
  3. Recipe: These are the shell commands (like gcc) that actually perform the build. Important: The recipe line must start with a Tab character, not spaces.

Putting it into practice

Imagine you have a program called hello that depends on a source file named main.c. Here is how you would write that rule:

# The target is the 'hello' executable
# The dependency is 'main.c'
hello: main.c
	gcc main.c -o hello

When you run the command make in your terminal, the tool looks at this rule. It checks the "Last Modified" timestamp of main.c. If main.c is newer than the existing hello file, or if hello doesn't exist yet, it runs the gcc command. If nothing has changed, make smartly informs you that the target is "up to date" and does nothing, saving you time.

Chaining rules

You can also chain rules together. If your executable depends on an object file, and that object file depends on a source file, make will follow the trail:

# Final executable depends on the object file
app: main.o
	gcc main.o -o app

# Object file depends on the C source
main.o: main.c
	gcc -c main.c -o main.o

In this setup, if you change main.c, make realizes main.o is outdated, rebuilds it, and then realizes app is also outdated and rebuilds that too.

Key takeaway

A Makefile rule uses targets (the goal), dependencies (the requirements), and recipes (the commands) to automate your build process efficiently.