makefile的自动推导

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 $< > $@ >[email protected]; \
        sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < [email protected] > $@; \
        rm -f [email protected]

.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 $< > $@ >[email protected]; \
        sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < [email protected] > $@; \
        rm -f [email protected]

会生成一个.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 $< > $@ >[email protected]; \
        sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < [email protected] > $@; \
        rm -f [email protected]

.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

猜你喜欢

转载自blog.csdn.net/weixin_33978044/article/details/87037697
今日推荐