Below is a Makefile cheat sheet:
Makefile Basics
Rule Syntax
target: prerequisites
recipe
target: The target file or action to be built.
prerequisites: Files or dependencies required for building the target.
recipe: The set of commands to build the target.
Variables
VAR_NAME = value
Assign a Variable: CC = gcc
Use a Variable: $(CC) -o output_file input_file.c
Comments
# This is a comment
Phony Targets
.PHONY: target_name
Declare a Phony Target: Avoid conflicts with files having the same name.
Makefile Examples
Simple Rule
hello: hello.c
gcc -o hello hello.c
1. Simple Rule
Explanation: Builds an executable hello
from the hello.c
source file.
Variables and Automatic Variables
CC = gcc
CFLAGS = -Wall -Werror
hello: hello.c
$(CC) $(CFLAGS) -o hello hello.c
Explanation: Uses variables for compiler and flags.
Automatic Variables
CC = gcc
CFLAGS = -Wall -Werror
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
Explanation: Uses automatic variables ($@
, $<
) for generic rule.
Wildcard Function
SOURCE_FILES = $(wildcard *.c)
Explanation: Gets a list of source files ending with .c
.
Conditional Statements
DEBUG = 1
ifeq ($(DEBUG), 1)
CFLAGS += -g
else
CFLAGS += -O2
endif
Explanation: Adds debugging flags if DEBUG
is set to 1.
Include Other Makefiles
include other_makefile.mk
Explanation: Includes another Makefile.
Makefile Tips
Use Tab for Recipes
- Always use a tab character (not spaces) at the beginning of the recipe lines.
Dependency Chain
- Make sure to define dependencies accurately to trigger rebuilds when needed.
Keep It Modular
- Break down complex Makefiles into smaller, modular components.
Use Implicit Rules
- Leverage implicit rules to simplify the Makefile.
Error Handling
- Use
-
before commands to continue despite errors.
This cheat sheet provides a basic overview of Makefile syntax and usage. For more details and advanced features, refer to the official documentation.