Makefile Portable POSIX Patterns

Portable makefile patterns that work across POSIX make environments, avoiding GNU-only features when needed.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Portable make basics
POSIX-style portable rule
all: app

app: main.o util.o
  cc -o app main.o util.o

# Write simple, explicit file rules compatible with standard make.

Use standard macros
CC = c99
CFLAGS = -O2
LDFLAGS =
LDLIBS =

app: main.o util.o
  $(CC) $(LDFLAGS) -o $@ main.o util.o $(LDLIBS)

# Honor user-overridable standard compiler variables.

Suffix rule
.SUFFIXES: .c .o
.c.o:
  $(CC) $(CFLAGS) -c $<

# Use classic suffix rules when targeting very portable make implementations.

Portable clean target
clean:
  rm -f app *.o

# Provide common non-file maintenance targets.

Override variables from CLI
make CC=clang CFLAGS='-O0 -g'

# Allow users to customize toolchain choices.

## Recipe portability
Use shell short-circuit safely
deploy:
  cd infra && terraform apply -auto-approve

# Stop on failure explicitly within one recipe line.

Escape dollar signs in recipes
print-pid:
  @echo $$PPID

# Pass `$` through to the shell.

Use tabs for recipe lines
target:
  printf 'hello
'

# Indent recipe commands with a tab character.

Create directory safely
build:
  mkdir -p build

# Ensure output directories exist.

## Features to avoid for portability
Avoid eval for POSIX portability
# Prefer explicit rules when portability matters
app: main.o util.o
  $(CC) -o $@ $^

# Prefer explicit rules over GNU metaprogramming.

Avoid GNU wildcard dependence
SRC = main.c util.c api.c

# List sources explicitly or generate files in configure scripts.

Avoid `.ONESHELL` when targeting POSIX make
release:
  cd dist && tar -czf app.tar.gz app

# Keep recipe-line semantics standard.

Recommended next

No recommendations yet.