Using variables in Makefiles
What you'll learn: How to use variables to make your build scripts cleaner, more flexible, and easier to update.
The Problem with Repetition
Imagine you are writing a long list of instructions for a chef. Every time you mention an ingredient, you write out "Organic, Farm-Raised, Extra-Large Grade A Brown Eggs." If the chef decides to switch to "Standard White Eggs," you have to hunt through every page of your recipe to change that long phrase.
In a Makefile, you often repeat the name of your compiler (gcc) or your output file name. If you decide to change compilers or rename your project, manually editing every single line is tedious and prone to errors.
Using Variables as Shortcuts
In Makefiles, you can create variables (often called "macros") to store these repeated strings. By convention, these are written in uppercase. To create one, use the equals sign: NAME = value. To use it later, wrap the name in a dollar sign and parentheses: $(NAME).
Think of a variable like a "Find and Replace" shortcut. When make runs, it simply swaps the shortcut for the actual text before executing the command.
A Practical Example
Here is a Makefile that uses variables for the compiler (CC), the compiler flags (CFLAGS), and the final executable name (TARGET).
# Define our variables
CC = gcc
CFLAGS = -Wall -g
TARGET = my_app
# Use the variables with $(NAME)
$(TARGET): main.c
$(CC) $(CFLAGS) main.c -o $(TARGET)
clean:
rm -f $(TARGET)
In this example, if you want to turn off debugging symbols (the -g flag), you only have to change it in one spot at the top. If you decide to use a different compiler like clang, you just update the CC variable.
Why This Matters
Variables separate the configuration of your build from the logic of your build. The rules (the "how-to") stay the same, while the settings (the "what") stay at the top where they are easy to find. This makes your build scripts "DRY"—Don't Repeat Yourself.
Key takeaway
Variables allow you to define a value once and reuse it throughout your Makefile, making your build process easier to maintain and update.