Makefile:multiple sub-folders

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值