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

Automatic variables like `$@` and `$<`

Automatic variables like $@ and $<

What you'll learn: How to use shorthand symbols to make your Makefiles more concise and easier to maintain.

The problem with repetition

In a Makefile, you often find yourself typing the same filenames over and over. For example, if you want to compile main.c into an output file called app, you might write:

app: main.c
	gcc main.c -o app

Notice how app and main.c appear twice? In a large project with dozens of files, this duplication makes your Makefile cluttered. If you decide to rename your program, you have to hunt through every line to update the names. This is where automatic variables come in—they are like "pronouns" for your build rules.

Using @and@ and <

Think of automatic variables as placeholders that Make fills in for you at the moment the command runs. The two most common ones are:

  • $@: Refers to the target (the thing you are trying to build).
  • $<: Refers to the first dependency (the source file needed to build it).

Imagine a chef following a recipe. Instead of saying "Put the potato in the oven until the potato is cooked," the recipe says "Put the input in the oven until the result is ready."

Here is how we rewrite our previous example using these variables:

# The target is 'app', the dependency is 'main.c'
app: main.c
	gcc $< -o $@

When you run make, Make sees $@ and thinks, "The target is app, so I'll put that there." It sees $< and thinks, "The first dependency is main.c, so I'll put that there." The actual command executed remains gcc main.c -o app.

Why use them?

The power of these variables is most obvious when you use pattern rules. If you have ten different .c files that all need to be turned into .o (object) files, you don't want to write ten separate rules. You can write one "template" rule:

# For ANY .o file, look for a matching .c file
%.o: %.c
	gcc -c $< -o $@

Because of $@ and $<, this single rule works for logger.o, math_utils.o, or player.o without you ever having to type those names manually. It keeps your build process flexible and "DRY" (Don't Repeat Yourself).

Key takeaway

Automatic variables like $@ (target) and $< (first dependency) act as placeholders that make your Makefile shorter and easier to update.