Makefile
CC := clang
CFLAGS := -Wall -Wextra
CFLAGS_DEFAULT := -O3 -g
CFLAGS_DEBUG := -O0 -g -D__DEBUG__
LDFLAGS := -lpthread
BUILD_DIR := ../build/
TARGET := main
SOURCES := $(wildcard *.c)
HEADERS := $(wildcard *.h)
define rules
BUILD_DIR_$(1) := $(BUILD_DIR)$(1)/
TARGET_$(1) := $$(BUILD_DIR_$(1))$(TARGET)
OBJS_$(1) := $$(SOURCES:%.c=$$(BUILD_DIR_$(1))%.o)
.PHONY: $(1)
$(1): $$(TARGET_$(1))
$$(TARGET_$(1)): $$(OBJS_$(1))
$$(CC) $$(CFLAGS) -o $$@ $$+ $$(LDFLAGS)
$$(BUILD_DIR_$(1))%.o: %.c $(HEADERS)
@mkdir -p `dirname "$$@"`
$$(CC) $$(CFLAGS) -o $$@ -c $$<
endef
# $(info $(call rules,default))
$(eval $(call rules,default))
$(eval $(call rules,debug))
default: CFLAGS += $(CFLAGS_DEFAULT)
debug: CFLAGS += $(CFLAGS_DEBUG)
debug:
$(TARGET_debug)
.PHONY: clean
clean:
rm -rf $(BUILD_DIR)
ビルドはmakeまたはmake debugで実行できます。
makeはmake defaultと同義です。
ビルド後のディレクトリ構造はこうなります
build
debug
inc.o
main
main.o
default
inc.o
main
main.o
src
inc.c
inc.h
main.c
Makefile
evalに聞き覚えがない人はこちらのリンクを参考してください。
https://www.gnu.org/software/make/manual/html_node/Eval-Function.html