美文网首页开发环境搭建
makefile的自动推导

makefile的自动推导

作者: DayDayUpppppp | 来源:发表于2019-01-28 23:37 被阅读5次

main.c 文件

#include <stdio.h>
int main()
{
        printf("mian \n");
        return 0;
}

test.c 文件

#include <stdio.h>
int val2 = 100;

Makefile 文件

%.d:%.c
        g++ -MM $< > $@ >$@.tmp; \
        sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.tmp > $@; \
        rm -f $@.tmp

.PHONY: clean

sources = test.c main.c 
include $(sources:.c=.d)

main:main.o test.o
        g++ $^ -o $@
clean:
        rm *.o

然后就可以编译出可执行文件了。


Makefile的推导过程

知识点1:

test.o:test.c

上面这一条命令等价于 ,因为makefile会自动的补全这样的命令。

test.o:test.c
  g++ test.c -c test.o

知识点2:

%.d:%.c
        g++ -MM $< > $@ >$@.tmp; \
        sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.tmp > $@; \
        rm -f $@.tmp

会生成一个.d 文件

test.o test.d : test.c

知识点3:

include $(sources:.c=.d)

等价于

include test.d main.d 

等价于 把对应的.d文件导入到makefile中

test.o test.d : test.c

再根据知识点1,这一条语句变成了这样。

test.o test.d : test.c
    g++ test.c -o test.c

于是,上面的makefile变成

%.d:%.c
        g++ -MM $< > $@ >$@.tmp; \
        sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.tmp > $@; \
        rm -f $@.tmp

.PHONY: clean

sources = test.c main.c 

test.o test.d : test.c
      g++ test.c -o test.c
main.o main.d : main.c
      g++ main.c -o main

main:main.o test.o
        g++ $^ -o $@
clean:
        rm *.o

相关文章

网友评论

    本文标题:makefile的自动推导

    本文链接:https://www.haomeiwen.com/subject/vjqtsqtx.html