1st:you must konw that if there are mutiple subfolders, for example ‘function’ , ‘function/function1’, ‘function/function2’ and so on, under your current Makefile, a ‘built-in.o’ file,which is linked by main(outmost) Makefile, must exsit in every sub-folder.
2nd:Moreover, the ‘built-in.o’ file is created by linking all .o files generated by .c files under curret directory.
the following is main(outmost) Makefile
#target file
TGT = a.out
#source files(.c file)
SRCS=function1.c main.c function2.c ...
#all folders in current directory
SUB_DIR = main function
#"export" means that the variables can be used for every subdirctory.
export SUB_TGT = built-in.o # this is a general file which be finally used to linked in every folder.
export CC = gcc # compiler
export RM = rm # delete
export CUR_DIR = $(shell pwd) # perform shell command 'pwd'
export HEAD_DIR = $(CUR_DIR)/include # designate the location of header file
export CFLAGS = -I$(HEAD_DIR) # add -I
# link all SUB_TGT (built-in.o) and generate the final executable file (a.out).
$(TGT):$(SUB_DIR)
$(CC) $(CFLAGS) $(^:=/$(SUB_TGT)) -o $@
# go into every subdirctory and perform 'make' command in every subdirctory.
$(SUB_DIR):
make -C $@
clean:
$(RM) -rf $(TGT) $(SRCS:.c=.dep)
for dir in $(SUB_DIR); do\ # perform 'clean' command in all subdirectory
make -C $$dir clean; done
.PHONY:$(SUB_DIR)
the following is subdirectory Makefile
SRCS = *all .c files under the current files*
SUB_DIR = *subdirectory name if any*
$(SUB_TGT):$(SRCS:.c=.o) $(SUB_DIR)
$(LD) $(SRCS:.c=.o) $(SUB_DIR:=/$(SUB_TGT)) -r -o $@ #the differrnt between 'gcc' and 'ld -r' is the latter cannot link the C library but just these .o files.
#continue to perform the 'make' command in subdirectory if they exist.
$(SUB_DIR):
make -C $@
#Refer to the outermost 'Makefile' file
clean:
$(RM) -rf $(SUB_TGT) $(SRCS:.c=.o)
for dir in $(SUB_DIR); do make -C $$dir clean; done
.PHONY:$(SUB_DIR)