Makefile by Example: Variables
Variables allow you to define text strings once and substitute them in multiple places. This example demonstrates assignment and usage.
Code
# Define variables
CC = gcc
CFLAGS = -Wall -g
OBJ = main.o utils.o
TARGET = app
# Use variables with $(VAR_NAME)
$(TARGET): $(OBJ)
$(CC) $(CFLAGS) -o $(TARGET) $(OBJ)
main.o: main.c
$(CC) $(CFLAGS) -c main.c
utils.o: utils.c
$(CC) $(CFLAGS) -c utils.c
clean:
rm -f $(TARGET) $(OBJ)Explanation
Variables in Makefiles (often called macros) are similar to variables in other languages. They allow you to define a value once and use it throughout the file. This makes the Makefile easier to maintain. For example, if you want to change the compiler from gcc to clang, you only need to change the CC variable definition.
Variables are defined using the = operator (recursive expansion) or := (simple expansion). You access the value of a variable using $(VAR_NAME) or ${VAR_NAME}. It is standard convention to use uppercase names for variables, such as CC for the C compiler and CFLAGS for compiler flags.
Make also provides automatic variables that are set for each rule. For example, $@ refers to the target name, and $^ refers to all dependencies. Using these can further simplify your rules and reduce repetition, as we will see in later examples.
Code Breakdown
CC = gcc defines the compiler. This is a standard variable name used by implicit rules too.$(TARGET) expands to app. Make replaces the variable string before executing the command.
