Makefile——书写命令

命令要求

make每条规则中的命令和操作系统Shell的命令行是一致的,为啥这么讲呢? 因为make的命令默认是被“/bin/sh”——UNIX的标准Shell解释执行的。

每条命令的开头必须以Tab键开头,除非,命令是紧跟在prerequisites(依赖规则)后面的分号后的。

在命令行之间中的空格或是空行会被忽略,但是如果该空格或空行是以Tab键开头的,那么make会认为其是一个空命令。

显示命令

@

make会把其要执行的命令行在命令执行前输出到屏幕上。当我们用“@”字符在命令行前,那么,这个命令将不被make显示出来

[root@localhost ~]# cat makefile 
hello:
    echo hello world
[root@localhost ~]# make
echo hello world
hello world
View Code
[root@localhost ~]# cat makefile 
hello:
    @echo hello world
[root@localhost ~]# make
hello world
View Code

-n或--just-print

只是显示命令,但不会执行命令,这个功能很有利于我们调试我们的Makefile,看看我们书写的命令是执行起来是什么样子的或是什么顺序的。

[root@localhost ~]# cat makefile 
hello:
    @echo hello world
[root@localhost ~]# make -n
echo hello world
[root@localhost ~]# make --just-print
echo hello world
View Code

-s或--slient

全面禁止命令的显示。

[root@localhost ~]# cat makefile 
hello:
    @echo hello world
[root@localhost ~]# make -s
hello world
[root@localhost ~]# make --silent
hello world
View Code

命令执行

当prerequisites新于targets时,make会一按顺序一条一条的执行命令。

当要执行的 命令较多时,其中某2条命令,后一条命令需要在前一条命令结果之上执行时,你应该使用分号分隔这两条命令。上代码

[root@localhost ~]# cat makefile 
hello:
    cd /home/ziqiang
    pwd
    touch win10.txt
    echo haha > win10.txt
[root@localhost ~]# make
cd /home/ziqiang
pwd
/root
touch win10.txt
echo haha > win10.txt
[root@localhost ~]# ll | grep win
-rw-r--r--. 1 root root        5 Aug 13 20:29 win10.txt
[root@localhost ~]# cat win10.txt 
haha
View Code

cd命令并没有起作用,因此win10.txt文件并没有在/home/ziqiangm目录存在。

使用分号分隔这两条命令,上代码

[root@localhost ~]# cat makefile 
hello:
    cd /home/ziqiang;pwd;touch win10.txt;echo 666 > win10.txt
    echo haha > win10.txt
[root@localhost ~]# make
cd /home/ziqiang;pwd;touch win10.txt;echo 666 > win10.txt
/home/ziqiang
echo haha > win10.txt
[root@localhost ~]# ll | grep win
-rw-r--r--. 1 root root        5 Aug 13 20:37 win10.txt
[root@localhost ~]# cat win10.txt 
haha
[root@localhost ~]# ll /home/ziqiang/ | grep win
-rw-r--r--. 1 root    root     4 Aug 13 20:37 win10.txt
[root@localhost ~]# cat /home/ziqiang/win10.txt 
666
View Code

代码里创建了2个win10.txt,第一个在/home/ziqiang目录下,第二个在当前目录下。

echo haha > win10.txt这条命令另起炉灶,并没有接着上边命令继续执行,echo的输出重定位创建了文件win10.txt。

这段代码说明了要想命令前后影响能接上就得加;串起来(操蛋的设定)

命令出错

当prerequisites新于targets时,make会执行指令。每当命令运行完后,make会检测每个命令的返回码,如果命令返回成功,那么make会执行下一条命令,当规则中所有的命令成功返回后,这个规则就算是成功完成了。如果一个规则中的某个命令出错了(命令退出码非零),那么make就会终止执行当前规则,这将有可能终止所有规则的执行。

make执行指令返回非零值就一定是错误吗?

:不一定。比如mkdir,如果要创建的目录之前不存在,则返回0。如果已存在,则返回非零。但这并不是错误

命令前加-

为了做到不因命令的返回错误终止规则的运行,可以在Makefile的命令行前加一个减号“-”(在Tab键之后),标记为不管命令出不出错都认为是成功的。

clean:
        -rm -f *.o
View Code

-i或是--ignore-errors

Makefile中所有命令都会忽略错误。

-k或是--keep-going

如果某规则中的命令出错了,那么就终目该规则的执行,但继续执行其它规则。

以.IGNORE作为目标

如果一个规则是以“.IGNORE”作为目标的,那么这个规则中的所有命令将会忽略错误。

嵌套执行make

猜你喜欢

转载自www.cnblogs.com/kelamoyujuzhen/p/9470855.html
今日推荐