Make
For more details, refer to the GNU Make documentation.
Basic Syntax
Makefile Structure
A Makefile typically contains:
- Targets: The goal you want to build (e.g., an executable or object file).
- Dependencies: The files that the target depends on.
- Commands: The shell commands to execute to build the target.
Example
# Compile an object file
main.o: main.c
gcc -c main.c
# Link object files to create an executable
main: main.o utils.o
gcc -o main main.o utils.o
# Clean up
clean:
rm -f main *.o
Variables
Defining Variables
Variables allow you to reuse values throughout your Makefile.
Using Variables
Use $(VAR_NAME)
to reference a variable.
Special Variables
Commonly Used Special Variables
$@
: The file name of the target.$<
: The first prerequisite (dependency).$^
: The list of all prerequisites.
Example
Pattern Rules
Compiling Multiple Files
Use pattern rules to define how to build files of a particular type.
Example with Multiple Files
Phony Targets
Defining Phony Targets
Phony targets are not actual files; they are simply names for commands you want to run.
Example with Phony Targets
Automatic Variables
List of Automatic Variables
$@
: The target name.$<
: The first prerequisite.$^
: All prerequisites.
Example Usage
Conditionals
Using Conditionals
Conditionals allow you to define variables or rules based on conditions.
Example with Conditionals
CC = gcc
ifeq ($(CC),gcc)
CFLAGS = -Wall -g
else
CFLAGS = -O2
endif
main: main.o utils.o
$(CC) $(CFLAGS) -o main main.o utils.o