Make is a powerful build automation tool that simplifies the process of compiling and building projects. This cheat sheet provides essential commands and directives to efficiently use Make for managing software builds.
Introduction:
Make uses a file called Makefile to define rules and dependencies for building software. It automates the build process by executing predefined commands based on the dependencies and their modification timestamps.
Basic Commands:
Command
Description
make
Build the default target in the Makefile.
make [target]
Build a specific target in the Makefile.
make -f [makefile]
Use a specified Makefile.
make -n or make --dry-run
Display the commands without executing them.
make -B or make --always-make
Force a rebuild of all targets.
Variables and Assignments:
Command
Description
CC = gcc
Assign the compiler (e.g., gcc) to a variable.
CFLAGS = -Wall -O2
Set compilation flags for the C compiler.
LDFLAGS = -lm
Set linker flags for the linker.
SOURCES = file1.c file2.c
Define a list of source files.
OBJECTS = $(SOURCES:.c=.o)
Generate object file names from source files.
Targets and Dependencies:
Command
Description
all: [dependencies]
Define the default target and its dependencies.
target: [dependencies]
Define a custom target and its dependencies.
$(target): [dependencies]
Define a variable-based target and dependencies.
.PHONY: [target]
Declare a target as phony (non-file target).
Pattern Rules and Wildcards:
Command
Description
%.o: %.c
Define a pattern rule for compiling source files.
$(wildcard pattern)
Expand to a list of files matching a pattern.
$(patsubst pattern,replacement,text)
Replace occurrences of a pattern in a text.
$(foreach var,list,text)
Iterate over elements in a list.
Conditionals and Control Flow:
Command
Description
ifeq ($(variable), value)
Conditionally execute commands if equal.
ifdef [variable]
Conditionally execute commands if defined.
ifndef [variable]
Conditionally execute commands if not defined.
else
Execute commands if the previous condition is false.
endif
End a conditional block.
Miscellaneous:
Command
Description
$(shell command)
Execute a shell command and use the result.
$(error message)
Display an error message and stop execution.
$(warning message)
Display a warning message during execution.
.SUFFIXES: .c .o
Define the default suffixes for implicit rules.
.DEFAULT_GOAL := [target]
Set the default goal if none is specified.
Conclusion
Make is a versatile tool for automating software builds and managing project dependencies. This cheat sheet provides a quick reference for common Make commands and syntax. Whether you are a beginner or an experienced developer, use these commands to streamline your build process and enhance your understanding of Makefile structures.