这是一个简单的Makefile:
all: actual.txt test1.txt test2.txt
actual.txt: header.txt actual_part1.txt actual_part2.txt footer.txt
cat $^ > $@
test1.txt: header.txt actual_part1.txt test1_part2.txt footer.txt
cat $^ > $@
test2.txt: header.txt test2_huge_part.txt footer.txt
cat $^ > $@
如您所见,所有三个目标都使用相同的命令构建,重复三次。是否有可能以某种方式减少重复?
答案 0 :(得分:1)
根据你提供的makefile,有几种方法。
一种是将配方放入变量中:
BLDTXT = cat $^ $@
all: actual.txt test1.txt test2.txt
actual.txt: header.txt actual_part1.txt actual_part2.txt footer.txt
$(BLDTXT)
test1.txt: header.txt actual_part1.txt test1_part2.txt footer.txt
$(BLDTXT)
test2.txt: header.txt test2_huge_part.txt footer.txt
$(BLDTXT)
这不会减少要写入的行数,但它确实允许您在一个地方更改配方。
另一种选择是创建单个规则并将先决条件定义移动到其他行,如下所示:
BLDTXT = cat $^ $@
ALLTXT = actual.txt test1.txt test2.txt
all: $(ALLTXT)
$(ALLTXT):
$(BLDTXT)
actual.txt: header.txt actual_part1.txt actual_part2.txt footer.txt
test1.txt: header.txt actual_part1.txt test1_part2.txt footer.txt
test2.txt: header.txt test2_huge_part.txt footer.txt