PHONY := __build
__build:

obj-y		:=
subdir-y	:=
libobj-y	:=
libsub-y	:=
include Makefile

# obj-y := a.o b.o c/ d/
# $(filter %/, $(obj-y))   : c/ d/
# __subdir-y  : c d
# subdir-y    : c d
__subdir-y	:= $(patsubst %/,%,$(filter %/, $(obj-y)))
subdir-y	+= $(__subdir-y)

__libsub-y	:= $(patsubst %/,%,$(filter %/, $(libobj-y)))
libsub-y	+= $(__libsub-y)

# c/built-in.o d/built-in.o
subdir_objs	:= $(foreach f,$(subdir-y),$(f)/built-in.o)

subdir_libs	:= $(foreach f,$(libsub-y),$(f)/built-in.a)
# a.o b.o
cur_objs	:= $(filter-out %/, $(obj-y))
lib_objs	:= $(filter-out %/, $(libobj-y))
#dep_files	:= $(foreach f,$(sort $(cur_objs) $(lib_objs)),.$(f).d)
#一般不会有重复项
dep_files	:= $(foreach f,$(cur_objs) $(lib_objs),.$(f).d)
dep_files	:= $(wildcard $(dep_files))

CURDIR		:= $(shell pwd)

ifneq ($(dep_files),)
  include $(dep_files)
endif


ifeq ($(strip $(lib_objs) $(subdir_libs)),)
	LIBNAME		:=
else
	ifeq ($(LIBNAME),)
		LIBNAME		:= built-in.a
	endif
endif

ifeq ($(strip $(cur_objs) $(subdir_objs)),)
	OBJNAME		:=
else
	ifeq ($(OBJNAME),)
		OBJNAME		:= built-in.o
	endif
endif

#构建静态库
define BUILD_LIBRARY
@echo CREATE $@ > ar.mac
$(foreach LIB, $(filter %.a, $^),
@echo ADDLIB $(LIB) >> ./ar.mac
)
@echo SAVE >> ./ar.mac
@echo END >> ./ar.mac
@$(AR) -M < ./ar.mac
$(if $(filter %.o,$^),@$(AR) -q $@ $(filter %.o, $^))
endef


alldir		:= $(sort $(subdir-y) $(libsub-y))

PHONY		+= $(alldir)

__build : $(OBJNAME) $(LIBNAME)
$(alldir):
	@echo $(CURDIR)/$@:
	make -C $@ -f $(TOPDIR)/Makefile.build

define DIR_RULE
#可以发现这里用的空命令(tab)，如果没有空命令会出现问题
$(1) : $$(patsubst %/,%,$$(dir $(1)))
	
endef

$(foreach v, $(subdir_objs), $(eval $(call DIR_RULE, $(v))))
$(foreach v, $(subdir_libs), $(eval $(call DIR_RULE, $(v))))

ifneq ($(OBJNAME),)
$(OBJNAME) : $(cur_objs) $(subdir_objs)
	@echo LD $(CURDIR)/$@
	@$(LD) -r -o $@ $^
endif


ifneq ($(LIBNAME),)
$(LIBNAME) : $(lib_objs) $(subdir_libs)
	@echo AR $(CURDIR)/$@
	$(BUILD_LIBRARY)
endif


dep_file = .$@.d

%.o : %.c
	@echo CC $(CURDIR)/$@
	@$(CC) $(CFLAGS) -Wp,-MD,$(dep_file) -c -o $@ $<

%.o : %.S
	@echo CC $(CURDIR)/$@
	@$(CC) $(CFLAGS) -Wp,-MD,$(dep_file) -c -o $@ $<
	
.PHONY : $(PHONY)