Makefile:如何写目标依赖

本文并不是Makefile的教程,仅是本人学习时的感悟。

Makefile的基本格式

目标:依赖文件(or 目标)
[tab]命令

目标: 是要生成的或操作的命令的索引
依赖: 是生成目标依赖的文件或目标
命令: 是为了生成目标需要执行的shell语句

任意一个依赖文件被改动,将导致已存在的目标文件过期,简单来说,依赖的作用就是决定目标是否过期,是否需要重新编译。

举个例子,

#include <stdio.h>  
#include "mylib1.h"  
#include "mylib2.h"  
  
int main(int argc, char argv[]){  
    printf("hello world!\n");  
}  

对应的Makefile可以是

helloworld: stdio.h mylib1.h mylib2.h other.o
    gcc -o helloworld helloworld.c

也可以是

helloworld: other.o
    gcc -o helloworld helloworld.c

前者希望在stdio.h、mylib1.h、mylib2.h、other.o被修改时重新执行helloworld目标,而后者仅仅希望检查other.o的修改。

目标依赖往往还有另外一种用法,用于执行其他目标。例如

.PHONY: all clean target

all: target clean

target: helloworld.o
    gcc helloworld.o -o helloworld

helloworld.o:
    gcc -c helloworld.c

clean:
    rm helloworld.o

执行all目标的时候,依赖另外两个目标targetclean。在执行all目标前,会优先执行目标targetclean

怎么判断all依赖的是目标还是文件

.PHONY: all

all: test
    @echo in all

test:
    @echo in test

执行这个Makefile时,当前目录下有无test文件会有两个不同的执行结果

[GMPY@11:24 tmp]$ll
总用量 4.0K
1186807 -rw-r--r-- 1 gmpy gmpy 57 4月   5 11:20 Makefile
[GMPY@11:24 tmp]$make
echo in test
in test
echo in all
in all
[GMPY@11:24 tmp]$touch test #创建test文件
[GMPY@11:24 tmp]$make
echo in all
in all
[GMPY@11:24 tmp]$

总结来说,判断依赖是目标还是文件,有以下两个规则:

  1. 优先检查当前目录下是否有同名文件,有则文件,无则目标
  2. .PHONY 标识的都是(伪)目标,不再检查文件是否存在

猜你喜欢

转载自www.cnblogs.com/gmpy/p/10658304.html
今日推荐