makefile函数与实例

2018-01-21  本文已影响183人  yangzai

函数

A = a b c
B = $(foreach f, $(A), $(f).o)
all:
    @each B = $(B)

输出: B = a.o b.o c.o 这样就能遍历A集合

C = a b c d/
D = $(filter %/,$(C))
E = $(filter-out %/,$(C))

all:
    @echo D = $(D)
    @echo E = $(E)

这里我们使用通配符%来匹配
输出: D = d/ E = a b c

filters = $(wildcard *.c)
all :
    @echo filters = $(filters)

输出:filters = a.c b.c c.c

files = a.c b.c c.c
dep_files = $(patsubst %.c, %.d,$(files))
all :
    @echo dep_files= $(dep_files)

输出:dep_files = a.d b.d c.d

实例

创建3个文件 a.c b.c c.c c.h
a.c文件:

#include <stdio.h>
void func_b();
void func_c();

int main(){
    func_b();
    func_c();
    return 0;
}

b.c文件:

#include <stdio.h>
void func_b(){
    printf("This is B\n");
}

c.c文件 依赖c.h文件,并使用C这个宏:

#include <stdio.h>
#include <c.h>
void func_c(){
    printf("This is C = %d\n", C);
}

c.h文件:

#define C 1

makefile文件:

test : a.o b.o c.o
    gcc -o test $^
%.o : %.c
    gcc -c -o $@ $<
clean:
    rm *.o test
.PHONY : clean

我们执行make 与./test指令,可以成功执行输出:
This is B
This is C = 1
当我们修改c.h文件中的#define C 2后再次运行make 与./test执行还是得到同样的输出,也就是我们修改的c.h文件没生效。
这主要是我们的c.o文件只依赖了c.c文件。我们加上c.o : c.c c.h两个依赖即可:

test : a.o b.o c.o
    gcc -o test $^
c.o : c.c c.h
%.o : %.c
    gcc -c -o $@ $<
clean:
    rm *.o test
.PHONY : clean

再次执行make 与./test则正常输出:
This is B
This is C = 2
所以我们要给.o文件加上.h的依赖。但是.h有很多,手动添加很麻烦,makefile给我们提供了自动生成依赖的功能。

test : a.o b.o c.o
    gcc -o test $^
c.o : c.c c.h
%.o : %.c
    gcc -c -o $@ $< -MD -MF .$@.d 
clean:
    rm *.o test
.PHONY : clean

会生成多个.a.o.d 、.b.o.d 、 .c.o.d依赖文件
这样我们就可以把这些依赖文件添加到makefile文件中
条件是:只有.o.d文件存在才添加

objs = a.o b.o c.o
#将objs文件都加上.开始.d结束
def_files := $(patsubst %,.%.d,$(objs))
#判断def_files是否存在,如果存在则包含进来
def_files := $(wildcard $(def_files))

test : $(objs)
    gcc -o test $^

ifneq ($(def_files),)
#如果存在则包含进来
include $(def_files)
endif

%.o : %.c
    gcc -c -o $@ $< -MD -MF .$@.d

clean : 
    rm *.o test

distclean:
    rm $(def_files)

.PHONY : clean

这时候我们使用make与 ./test则输出:
This is B
This is C = 2
我们再次修改#define C 3
再次make 与 ./test则输出
This is B
This is C = 3
这样我们就不用手工添加.o文件依赖.h文件了,让makefile自动包含依赖

上一篇 下一篇

猜你喜欢

热点阅读