我正在尝试编写一个非常简单的Makefile,但我无法使其正常工作。
target_a : file.txt
echo "this is target_a"
touch 0_$@
target_b : 0_target_a
echo "executing target_b"
touch 0_$@
每当我运行make taget_b
时,都会发出错误消息:
make: *** No rule to make target '0_target_a', needed by 'target_b'. Stop.
我可以将touch 0_$@
更改为touch $@
。但是我真的想要touch 0_$@
(文件名的自由选择)的解决方案。
从GNU手册页ftp://ftp.gnu.org/old-gnu/Manuals/make-3.79.1/html_chapter/make_2.html
目标通常是程序生成的文件的名称;目标的示例是可执行文件或目标文件。目标也可以是要执行的动作的名称
我想知道当目标名称为an时如何构建Make依赖项:
动作
答案 0 :(得分:1)
I am afraid you cannot directly do just that and you'd have to help yourself with an intermediate target that makes the connection between target and its output clear (and hence gives make a chance to decide when it does or does not need to be remade:
0_target_a: file.txt
echo "this is target_a"
touch $@
target_b: 0_target_a
echo "executing target_b"
touch 0_$@
I.e. defining rule for target 0_target_a
and updating touch
accordingly will give you the behavior you wanted as make now understand the rule the connection between target and file 0_target_a
and know when it does not need to be remade as a dependency of target_b
. Now if you still want to also have a standalone target_a
that would generate file 0_target_a
, you can define it as follows:
target_a: 0_target_a
Since we know this target is not really creating a file itself, we can spare make a little effort looking for its result (target_a
) and also prevent clashes should such file be created by declaring it as phony.
As a matter of fact you may want to give your target_b
the same treatment, as otherwise (again make does not have enough information to understand the relation between target_b
and 0_target_b
) make target_b
is always remade even though the file has already been generated.
The whole make file would look like this:
.PHONY: target_a target_b
target_a: 0_target_a
target_b: 0_target_b
0_target_a: file.txt
echo "this is target_a"
touch $@
0_target_b: 0_target_a
echo "executing target_b"
touch $@
If that is a reoccurring theme throughout the file, you could also express the relation on second and third line by defining a static pattern rule:
target_a target_b: %: 0_%
This defines a rule that a any target (first '%' without anything else) has a prerequisite of 0_
prefix followed by that target name (0_%
, 0_
plus stem which in this case is a target name in its entirety as matched by previous %
). and makes this rule applicable to targets target_a
and target_a
. This rule has no recipe and hence only describe target/prerequisite relation between the two.
In other words it means the same thing as the full example lines 2 and 3 combined.
答案 1 :(得分:0)
target_b
的依赖项本身应该是有效的目标,或者是已经存在的文件
target_a : file.txt
echo "this is target_a"
touch 0_$@
target_b : target_a
echo "executing target_b"
touch 0_$@
如果您想将0_target_a
文件的创建“别名”到target_a
“操作”中,则可以添加中间规则:
0_target_a : file.txt
echo "creating 0_target_a"
touch 0_$@
target_a : 0_target_a
target_b : target_a
echo "executing target_b"
touch 0_$@