我们从一个最简单的makefile说起,请看如下makefile:
all:
@echo "Hello Danny,Let's start the trip of Makefile learning trip!"
test:
@echo "Testing Makefile target!"
运行:
# make all
Hello Danny,Let's start the trip of Makefile learning trip!
# make test
Testing Makefile target!
可以看到,makefile有一定的规则。当make all时,我们会执行all这个目标分支,并执行相应的命令;对于make test,可以得到同样的分析。
Makefile的规则由目标、先决条件及命令组成。可按如下格式理解:
target ... : prerequisites ...
command
目标和先决条件之间是一种依赖关系。在构建目标之前,必须保证先决条件(prerequistes)已经构建。
详细解读:
(1)当运行make命令,且在make后不带参数,将默认执行第一个规则。
例如前面的的makefile,如果只运行make,将默认找到一个target all,执行第一条规则。执行结果:
# make
Hello Danny,Let's start the trip of Makefile learning trip!
该运行结果与make all结果一样。
假如假如all 和test的位置换下,让test 成为第一个target,即将makefile改为:
test:
@echo "Testing Makefile target!"
all:
@echo "Hello Danny,Let's start the trip of Makefile learning trip!"
则运行结果为:
# make
Testing Makefile target!
该运行结果与make test结果一样。
(2)可以在makefile中通过default指定和定制默认目标。例如:
default:test
all :
@echo "Hello Danny,Let's start the trip of Makefile learning trip!"
test:
@echo "Testing Makefile target!"
这样,默认make将执行test分支。
(3)一条规则的target可以有多个.
例如,给第一条规则添加一个init目标,即将makefile改为:
all init :
@echo "Hello Danny,Let's start the trip of Makefile learning trip!"
test:
@echo "Testing Makefile target!"
这样make init和make all都将得到一样的结果。
(4)prerequisites依赖条件可以为0到多个。
all init :test
@echo "Hello Danny,Let's start the trip of Makefile learning trip!"
test:
@echo "Testing Makefile target!"
运行make,将先执行依赖条件test,然后再执行本规则的命令。所以,结果如下:
# make
Testing Makefile target!
Hello Danny,Let's start the trip of Makefile learning trip!
(5)command前需要加tab键,否则就不符合make的语法。
(6)规则可以为多个.前面的makefile都包含了2个规则,可以根据需要添加规则。