Makefile [*.d]自动依赖

-------------------------------------------

文件:
bin     main.d  Makefile   test.c  test.h  tm.c  tm.o
main.c  main.o  Makefile~  test.d  test.o  tm.d
-------------------------------------------

SRC := $(wildcard *.c)

OBJS := $(patsubst %.c, %.o, $(SRC))

all: bin

%d : %c
    set -e; rm -f $@; \
    $(CC) -MM $< > $@.$$$$; echo $@; \
    sed 's,\($*\)o[:]*,\1o $@ :,g' < $@.$$$$ > $@; \
    rm -f $@.$$$$

sinclude $(SRC:.c=.d)

bin : $(OBJS)
    echo $^
    $(CC) -o bin $^
    
clean:

    rm -f *.o bin *.d *.d.*


-------------------------------------------------

展开为:

SRC := $(wildcard *.c)
OBJS := $(patsubst %.c, %.o, $(SRC))

all: bin

%d : %c
    set -e; rm -f $@; \
    $(CC) -MM $< > $@.$$$$; echo $@; \
    sed 's,\($*\)o[:]*,\1o $@ :,g' < $@.$$$$ > $@; \
    rm -f $@.$$$$

test.o test.d : test.c test.h

bin : $(OBJS)
    echo $^
    $(CC) -o bin $^
    
clean:
    rm -f *.o bin *.d *.d.*

#########################################

sed 's,\($*\)o[:]*,\1o $@ :,g' < $@.$$$$ > $@; \

解析:

sample:

前:test.o: test.c test.h

后:test.o test.d : test.c test.h


$@ 表示 main.d test.d tm.d 中的main.d或 test.d, 或 tm.d, 每次只能成为一个。 %d:%c中的目标 %d的值。

$^ 表示集合 main.o test.o tm.o

$<表示依赖 %c的值, main.c或test.c或tm.c

-------------------------------------

test.o test.d : test.c test.h

表明test.o编译会关系到test.d, 而test.d又关联到test.c和test.h,所以只要test.c所引用到的头文件有所修改,都会重新编译test.o和test.d


-------------------------------------

执行结果:
set -e; rm -f tm.d; \
    cc -MM tm.c > tm.d.$$; echo tm.d; \
    sed 's,\(tm.\)o[:]*,\1o tm.d :,g' < tm.d.$$ > tm.d; \
    rm -f tm.d.$$
tm.d
set -e; rm -f test.d; \
    cc -MM test.c > test.d.$$; echo test.d; \
    sed 's,\(test.\)o[:]*,\1o test.d :,g' < test.d.$$ > test.d; \
    rm -f test.d.$$
test.d
set -e; rm -f main.d; \
    cc -MM main.c > main.d.$$; echo main.d; \
    sed 's,\(main.\)o[:]*,\1o main.d :,g' < main.d.$$ > main.d; \
    rm -f main.d.$$
main.d
cc    -c -o main.o main.c
cc    -c -o test.o test.c
cc    -c -o tm.o tm.c
echo main.o test.o tm.o
main.o test.o tm.o
cc -o bin main.o test.o tm.o
root@commander-LIFEBOOK-LH531:/home/samba/proj# cat test.d
test.o test.d : test.c test.h


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值