[GNU] 喝一杯咖啡, 写一写 Makefile

 

Makefile 是 Linux 下组织程序的一个工具,它的命令是 make。html

首字母M/m均可以git

 

【Makefile】github

Makefile 编写的主旋律:shell

target: [dependency]
(TAB)[command]

 

【make】ubuntu

了解支持的功能和选项:工具

$ man make     # 查看完整手册
$ make --help  # 快速查看格式和选项

 

用法示例:ui

# 指定 Makefile 文件为 build.mk,指定 target 是 all; -s 表示不输出任何系统提示.
$ make all -f build.mk -s

$
make [target] # 默认就是读取 Makefile,默认 target 是文件内首个 target 

 

【流程】this

make 命令读取 Makefile 和 target;spa

检查 target 的依赖是否有更新,有就执行 command,没有就提示目标文件已经是最新。code

 

一个统计 controbuter 的 Makefile:

# 原始代码:https://github.com/youzan/zan/blob/master/Makefile

usage = "\
Usage: make <option> authors"

default:
    @echo $(usage)

authors:
    @git log --format='%aN <%aE>' | sort -u > $@

 

@    不在终端显示执行的命令,等同于 make 加 -s 选项。

$@  等同于当前 target。

$^   当前 target 的全部依赖。

$<   当前 target 依赖中的第一个。

|      shell 的管道符。

>     shell 的覆盖写入标记。

 

【变量使用】

引用式(=),相互影响:

jack = $(mike)
mike = $(lucy)
lucy = 18

default:
    @echo $(jack) # 18
    @echo $(mike) # 18
    @echo $(lucy) # 18

除了赋值以外,特性跟 shell 彻底不同;shell 的等号两边是不容许空格的,且不是引用式的。 

 

展开式(:=),只取前面变量的值:

jack := $(mike)
mike := $(lucy)
lucy = 18
lucy ?= 19
bob = 20
bob += 16
default: @echo $(jack) # 空
@echo $(mike) # 空 @echo $(lucy) # 18
@echo $(bob) # 20 16

  

变量为空时才进行赋值(?=).

值追加到变量末尾(+=).

 

【伪目标】

hello: 
    touch hellomake

#.PHONY: hellomake hellomake:
echo "this is hellomake target."

clean:
rm -f hellomake

分析一下上面的文件:

make hello 或 make;不指定 target 默认是 hello,执行 `touch hellomake`.

make hellomake;提示 make: `hellomake' is up to date.

 

显然,make hellomake 获得了非预期效果,为了不这类冲突,须要排除此 target 成为目标文件;

打开注释 .PHONY: hellomake 用来标示伪目标,而后再执行上面命令就是执行`rm -f hellomake`.

注意当 hellomake 文件不存在时,make hellomake 是能够执行它下面的命令的。

 

【补充】

Makefile 隐含规则

A Simple Makefile Tutorial

GNU make 

Autoconf 

 

Link : http://www.cnblogs.com/farwish/p/6148023.html

相关文章
相关标签/搜索