クイックリファレンス

Makefile / GNU Make チートシート

GNU Make の総合リファレンス:変数代入の種類、自動変数、コマンド接頭辞、文字列置換・フィルタ関数、条件分岐、CLI オプションを解説。

· 公開日

GNU Make は、Makefile と呼ばれる定義ファイルを読み取り、ソースコードから実行ファイルやライブラリを自動ビルドするツールです。

変数の代入

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+)

自動変数(マジック変数)

レシピの実行中、Make はターゲットや前提ファイルを参照するための自動変数を提供します:

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")

レシピコマンドの接頭辞

接頭辞 動作
@ 実行前にコマンドを標準出力へエコーしない
- 0 以外の終了コードを無視する(エラー時もビルド継続)
+ Make を -n(ドライラン)で実行してもこのコマンドを実行する
build:
	@echo "Compiling binary..."
	-rm -rf temp/
	gcc -o main main.c

関数とファイルマッチング

ワイルドカードとシェル実行

js_files  := $(wildcard src/*.js)
all_files := $(shell find images/ -type f)

文字列置換とフィルタリング

# 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))

条件分岐

ifeq ($(CC),gcc)
  CFLAGS += -Wall -O2
else ifeq ($(CC),clang)
  CFLAGS += -Weverything
else
  CFLAGS += -O0
endif

コマンドラインオプション

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

リファレンス

関連テーマ