C/C++用のMakefile

こちらを参照しながらバッと書いたもの。
設定エリアの変数値を変更してバイナリファイル名やソースディレクトリ、コンパイラやそれに渡されるオプションを設定する事が出来ます。

coption はコンパイルオプションの、
loption はリンクオプションの略。

# ===== SETTING =====

binary                := a.out
binary-directory      := bin
object-directory      := obj
source-directory-list := .
object-extension      := o
source-extension-list := cpp c

compiler              := g++
coptions              := -W -Wall -std=c++17
loptions              := 

# ===================

source-to-object = $(object-directory)/$(basename $(notdir $1)).$(object-extension)

source-list := $(foreach extension,$(source-extension-list),$(foreach directory,$(source-directory-list),$(wildcard $(directory)/*.$(extension))))
object-list := $(foreach source,$(source-list),$(call source-to-object,$(source)))

$(binary): $(binary-directory) $(object-directory) $(object-list)
  $(compiler) $(object-list) $(loption) -o $(binary-directory)/$(binary)

define body
$(call source-to-object,$1): $1
   $(compiler) -c $(coptions) $1 -o $(call source-to-object,$1)

endef
$(eval $(foreach source,$(source-list),$(call body,$(source))))

$(binary-directory):
   @mkdir -pv $@

$(object-directory):
   @mkdir -pv $@

.PHONY: all
.PHONY: clean

all: $(binary)

clean:
   @rm -fv $(binary-directory)/$(binary) $(object-list)