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
然后就可以編譯出可執(zhí)行文件了。
Makefile的推導(dǎo)過程
知識(shí)點(diǎn)1:
test.o:test.c
上面這一條命令等價(jià)于 ,因?yàn)閙akefile會(huì)自動(dòng)的補(bǔ)全這樣的命令。
test.o:test.c
g++ test.c -c test.o
知識(shí)點(diǎn)2:
%.d:%.c
g++ -MM $< > $@ >$@.tmp; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.tmp > $@; \
rm -f $@.tmp
會(huì)生成一個(gè).d 文件
test.o test.d : test.c
知識(shí)點(diǎn)3:
include $(sources:.c=.d)
等價(jià)于
include test.d main.d
等價(jià)于 把對應(yīng)的.d文件導(dǎo)入到makefile中
test.o test.d : test.c
再根據(jù)知識(shí)點(diǎn)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