Makefile Cheat Sheet

From WikiOD

Here is the cheatsheat of Makefile and basic guide on how to use Makefile

Var assignment[edit | edit source]

foo  = "bar"
bar  = $(foo) foo  # dynamic (renewing) assignment
foo := "boo"       # one time assignment, $(bar) now is "boo foo"
foo ?= /usr/local  # safe assignment, $(foo) and $(bar) still the same
bar += world       # append, "boo foo world"
foo != echo fooo   # exec shell command and assign to foo
# $(bar) now is "fooo foo world"

= expressions are only evaluated when they’re being used.

Magic variables[edit | edit source]

out.o: src.c src.h
  $@   # "out.o" (target)
  $<   # "src.c" (first prerequisite)
  $^   # "src.c src.h" (all prerequisites)

%.o: %.c
  $*   # the 'stem' with which an implicit rule matches ("foo" in "foo.c")

also:
  $+   # prerequisites (all, with duplication)
  $?   # prerequisites (new ones)
  $|   # prerequisites (order-only?)

  $(@D) # target directory

Command prefixes[edit | edit source]

Prefix Description
- Ignore errors
@ Don’t print command
+ Run even if Make is in ‘don’t execute’ mode
build:
    @echo "compiling"
    -gcc $< $@

-include .depend

Find files[edit | edit source]

js_files  := $(wildcard test/*.js)
all_files := $(shell find images -name "*")

Substitutions[edit | edit source]

file     = $(SOURCE:.cpp=.o)   # foo.cpp => foo.o
outputs  = $(files:src/%.coffee=lib/%.js)

outputs  = $(patsubst %.c, %.o, $(wildcard *.c))
assets   = $(patsubst images/%, assets/%, $(wildcard images/*))

More functions[edit | edit source]

$(strip $(string_var))

$(filter %.less, $(files))
$(filter-out %.less, $(files))

Building files[edit | edit source]

%.o: %.c
  ffmpeg -i $< > $@   # Input and output
  foo $^

Includes[edit | edit source]

-include foo.make

Options[edit | edit source]

make
  -e, --environment-overrides
  -B, --always-make
  -s, --silent
  -j, --jobs=N   # parallel processing

Conditionals[edit | edit source]

foo: $(objects)
ifeq ($(CC),gcc)
  $(CC) -o foo $(objects) $(libs_for_gcc)
else
  $(CC) -o foo $(objects) $(normal_libs)
endif

Recursive[edit | edit source]

deploy:
  $(MAKE) deploy2

Further reading[edit | edit source]

Credit:rstacruz