为子文件夹定义递归makefile的正确方法

时间:2016-08-11 02:00:27

标签: makefile

我有一个这样的项目:

main --> main.c uses tests/test.h
     |
     |_ tests (main/tests) --> test.h
               --> test1.c implementation of test.h
               --> test2.c implementation of test.h
               --> test3.c implementation of test.h

我目前有这样的makefile:

all: main.o tests/test1.o tests/test2.o tests/test3.o
        gcc -o main main.o tests/test1.o tests/test2.o tests3.o

%.o: %.c test.h
        gcc -c $< -o $@

但是我觉得它是重复的(比如我在main中有多个目录)。有没有更好的方法来使用递归make定义?

我是初学者,我只是想探索不同的方式。

1 个答案:

答案 0 :(得分:0)

不确定递归是什么意思,但是我把所有testx.o和testx.c放到2个列表中(实际上你的默认规则会拾取所有.c文件并将它们编译成.o文件)做这项工作:

OBJECTS=tests/test1.o tests/test2.o tests/test3.o ...
SOURCES=test1.c test2.c test3.c ...

all: main
main: main.o $(OBJECTS)
     gcc -o $@  $(OBJECTS)
%.o: %.c test.h
     gcc -c $< -o $@
相关问题