2015-07-20 109 views
1

下面是一个简单的Makefile:如何对不同的目标使用相同的命令?

all: actual.txt test1.txt test2.txt 

actual.txt: header.txt actual_part1.txt actual_part2.txt footer.txt 
    cat $^ > [email protected] 

test1.txt: header.txt actual_part1.txt test1_part2.txt footer.txt 
    cat $^ > [email protected] 

test2.txt: header.txt test2_huge_part.txt footer.txt 
    cat $^ > [email protected] 

正如你所看到的,所有三个目标都使用相同的命令而建,重复三次。是否有可能以某种方式减少重复?

回答

1

根据您提供的makefile,有几种方法。

一是把配方到一个变量:

BLDTXT = cat $^ [email protected] 

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 $^ [email protected] 
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 
+0

咦,不知道我可以有两个食谱为目标。谢谢,我想这几乎涵盖了它。 –

+1

你不能有两个_recipes_目标。但是,只要规则具有配方(配方是用于更新目标的脚本),您就可以拥有两个(或更多)_rules_目标。一些自动生成头文件相关性的工具会为每个先决条件编写一个单独的规则。 – MadScientist

相关问题