GNU Make es una herramienta de automatización de compilación que genera ejecutables y bibliotecas a partir de código fuente leyendo archivos Makefile.
Asignación de variables
foo = "bar" # Lazy (dynamically expanded when used)
bar = $(foo) foo # Dynamically references $(foo)
foo := "boo" # Immediate (simply expanded once at declaration)
foo ?= /usr/local # Conditional (assign only if foo is not already set)
bar += world # Append to existing value
foo != echo hello # Shell execution (GNU Make 4.0+)
Variables automáticas
Dentro de la ejecución de recetas, Make expone variables automáticas para referenciar objetivos y requisitos previos:
out.o: src.c src.h
$@ # "out.o" (the target name)
$< # "src.c" (first prerequisite)
$^ # "src.c src.h" (all prerequisites with duplicates omitted)
$+ # "src.c src.h" (all prerequisites preserving duplicates)
$? # Prerequisites newer than the target
$| # Order-only prerequisites
%.o: %.c
$* # The matched pattern stem ("foo" in "foo.c")
$(@D) # Directory part of the target ("build" in "build/out.o")
$(@F) # File part of the target ("out.o" in "build/out.o")
Prefijos de comandos de receta
| Prefijo | Comportamiento |
|---|---|
@ |
No mostrar el comando en stdout antes de ejecutarlo |
- |
Ignorar códigos de salida distintos de cero (continuar si falla) |
+ |
Ejecutar el comando aunque Make se lance con -n (simulación) |
build:
@echo "Compiling binary..."
-rm -rf temp/
gcc -o main main.c
Funciones y coincidencia de archivos
Comodines y Shell
js_files := $(wildcard src/*.js)
all_files := $(shell find images/ -type f)
Sustitución de cadenas y filtrado
# Extension substitution
objects = $(sources:.cpp=.o)
# Pattern substitution
outputs = $(patsubst src/%.c, build/%.o, $(wildcard src/*.c))
# Filter and filter-out
c_files = $(filter %.c, $(files))
non_c = $(filter-out %.c, $(files))
# Whitespace stripping
clean_var = $(strip $(dirty_var))
Condicionales
ifeq ($(CC),gcc)
CFLAGS += -Wall -O2
else ifeq ($(CC),clang)
CFLAGS += -Weverything
else
CFLAGS += -O0
endif
Opciones de línea de comandos
make -j 8 # Run parallel jobs (8 concurrent threads)
make -B, --always-make # Unconditionally build all targets
make -n, --dry-run # Print commands without executing
make -s, --silent # Do not print recipe commands
make -e # Environment variables override Makefile variables