Makefile中带反斜杠和不带反斜杠的多行命令之间的区别

5
在makefile中,

有什么不同?
targets : prerequisites
        recipe command \
        recipe command \
        ...

并且
targets : prerequisites
        recipe command
        recipe-command
        ...
2个回答

4

当通过反斜杠转义换行符连接多行文本时,它们将在同一个shell中运行。如果使用shell变量,则这可能很重要。当每个命令出现在自己的一行上时,它们将在新的shell中各自运行。


2
从GNU Make手册的第5.3节“配方执行”中:

When it is time to execute recipes to update a target, they are executed by invoking a new sub-shell for each line of the recipe, unless the .ONESHELL special target is in effect (see Using One Shell) (In practice, make may take shortcuts that do not affect the results.)

Please note: this implies that setting shell variables and invoking shell commands such as cd that set a context local to each process will not affect the following lines in the recipe.2 If you want to use cd to affect the next statement, put both statements in a single recipe line. Then make will invoke one shell to run the entire line, and the shell will execute the statements in sequence. For example:

foo : bar/lose
        cd $(@D) && gobble $(@F) > ../$@

Here we use the shell AND operator (&&) so that if the cd command fails, the script will fail without trying to invoke the gobble command in the wrong directory, which could cause problems (in this case it would certainly cause ../foo to be truncated, at least).

反斜杠的使用是为了将命令分成多行。详见手册中5.1 菜谱语法章节的详细解释。

在 make 解析菜谱时,会检查换行符前面是否有反斜杠。与普通的 Makefile 语法一样,通过在每个换行符前面加上反斜杠,可以将单个逻辑菜谱行拆分成多个物理行。这样的一系列行被视为单个菜谱行,并且将调用一个 shell 实例来运行它。


为了在单个 shell 中运行,整行代码需要用括号 '(' 和 ')' 包围起来。 - user3629249
@user3629249 不会。这样做会启动一个(无意义的)子shell。 - Etan Reisner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接