输入/输出对的Makefile

时间:2012-05-16 06:00:51

标签: makefile

我有一对输入/输出文件。我从脚本生成输出文件的名称:output=$(generate input)。例如,对可以是:

in1.c      out1.o
in2.txt    data.txt
in3        config.sh
sub/in1.c  sub/out1.o

所有这些对都遵循makefile中相同的规则集:

$(out): $(in) $(common) 
    $(run) $< > $@

编写这样一个Makefile的简洁有效的方法是什么?

我宁愿避免从另一个脚本生成Makefile。

3 个答案:

答案 0 :(得分:3)

我不会从脚本生成Makefile片段,但您可以使用include

INS := in1.c in2.txt in3 sub/in1.c

include rules.mk

rules.mk: Makefile
        rm -f $@
        for f in $(INS); do \
                out=`generate "$$f"`; \
                echo -e "$$out: $$f\n\t\$$(run) \$$<> > \$$@\n\n" >> $@; \
        done

答案 1 :(得分:3)

如果您include文件gmake将尝试生成并在任何其他目标之前包含它。将其与默认规则相结合可以让您接近您想要的内容

# makefile
gen=./generate.sh
source=a b c
run=echo

# Phony so the default rule doesn't match all
.PHONY:all
all:

# Update targets when makefile changes
targets.mk:makefile
    rm -f $@
    # Generate rules like $(target):$(source)
    for s in $(source); do echo "$$($(gen) $$s):$$s" >> $@; done
    # Generate rules like all:$(target)
    for s in $(source); do echo "all:$$($(gen) $$s)" >> $@; done

-include targets.mk

# Default pattern match rule
%:
    $(run) $< > $@

使用generate.sh进行测试

#!/bin/bash
echo $1 | md5sum | awk '{print $1}'

给我

$ make
rm -f targets.mk
for s in a b c; do echo "$(./generate.sh $s):$s" >> targets.mk; done
for s in a b c; do echo "all:$(./generate.sh $s)" >> targets.mk; done
echo a > 60b725f10c9c85c70d97880dfe8191b3
echo b > 3b5d5c3712955042212316173ccf37be
echo c > 2cd6ee2c70b0bde53fbe6cac3c8b8bb1

答案 2 :(得分:1)

  

编写这样一个Makefile的简洁有效的方法是什么?

可以给出一个输入列表和一个shell脚本,它生成输出文件名以使用GNU make功能生成目标,依赖项和规则:

all :

inputs := in1.c in2.txt in3 sub/in1.c
outputs :=

define make_dependency
  ${1} : ${2}
  outputs += ${1}
endef

# replace $(shell echo ${in}.out) with your $(shell generate ${in})
$(foreach in,${inputs},$(eval $(call make_dependency,$(shell echo ${in}.out),${in})))

# generic rule for all outputs, and the common dependency
# replace "echo ..." with a real rule
${outputs} : % : ${common}
    @echo "making $@ from $<"

all : ${outputs}

.PHONY : all 

输出:

$ make
making in1.c.out from in1.c
making in2.txt.out from in2.txt
making in3.out from in3
making sub/in1.c.out from sub/in1.c

在上面的makefile中,使用了强大的GNU make构造稍微使用的一个:$(eval $(call ...))。它请求make扩展宏以生成一段文本,然后将该段文本作为一个makefile进行评估,即make生成fly的makefile。