Makefile:如何写目标依赖

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

Makefile的基本格式

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

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

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

举个例子,

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

对应的Makefile可以是

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

也可以是

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

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

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

Copy
.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依赖的是目标还是文件

Copy
.PHONY: all all: test @echo in all test: @echo in test

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

Copy
[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 标识的都是(伪)目标,不再检查文件是否存在
posted @   广漠飘羽  阅读(1001)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示