2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

マルチモードでout of sourceビルドができるMakefileテンプレ

Posted at

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

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?