빠른 참조

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는 대상(target)과 선행 조건(prerequisite)을 참조하는 자동 변수를 제공합니다:

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

참고 자료

관련 주제