zoukankan      html  css  js  c++  java
  • Makefile:如何写目标依赖

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

    Makefile的基本格式

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

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

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

    举个例子,

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

    对应的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 标识的都是(伪)目标,不再检查文件是否存在
  • 相关阅读:
    MVC中权限管理
    ElasticSearch作为Windows服务启动
    linux下mysql常用的一些命令
    用Markdown写博客
    JAVA设计模式——简单工厂
    JAVA设计模式——单例模式
    JAVA设计模式——开篇
    Centos7.3安装和配置Mysql5.7
    java开发环境配置——IDEA SVN的使用
    java开发环境配置——IntelliJ IDEA
  • 原文地址:https://www.cnblogs.com/gmpy/p/10658304.html
Copyright © 2011-2022 走看看