Makefile将源文件从不同目录构建到同一对象目录中 [英] Makefile builds source files from different directories into the same object directory
问题描述
我有一个C项目,其目录布局是这样的
I have a c project with directory layout like this
src1
-a.c
-b.c
src2
-c.c
-d.c
objects
我正在尝试将a/b/c/d编译为目标文件并将其保存到objects目录中,这是我的Makefile的一部分.
I'm trying to compile a/b/c/d into objects files and saved them into objects directory and here is part of my Makefile.
src1 = src1/
src1 = src2/
obj = objects/
src1_files = a.c b.c
src2_files = c.c d.c
source_files = $(addprefix $(src1), $(src1_files)) $(addprefix $(src1), $(src2_files))
objects := $(addprefix $(obj), $(src1_files:.c=.o)) $(addprefix $(obj), $(src2_files:.c=.o))
$(obj)%.o: $(source_files)
$(CC) $(CFLAGS) -c $< -o $@
all: $(objects)
但是,当我尝试运行make时,却得到了以下内容.
However when I try to run make, I got the following.
gcc -Wall -c src1/a.c -o objects/a.o
gcc -Wall -c src1/a.c -o objects/b.o
gcc -Wall -c src1/a.c -o objects/c.o
gcc -Wall -c src1/a.c -o objects/d.o
有人知道为什么要这么做吗?
Anyone knows why is it doing that?
推荐答案
在阅读答案费利克斯·帕尔曼(Felix Palmen)之后,尤其是最后一句话
After having read the answer of Felix Palmen, especially the last sentence
如果您真的希望直接在对象目录中找到对象,则需要两种模式规则,一种匹配
src1
中的源,另一种匹配src2
中的源.
If you really want the objects directly in your objects directory, you need two pattern rules, one matching the sources in
src1
and one matching the sources insrc2
.
出于好奇,我相应地修改了Makefile
:
I modified the Makefile
accordingly (out of curiosity):
src1 = src1/
src2 = src2/
obj = objects/
src1_files = a.c b.c
src2_files = c.c d.c
source_files = $(addprefix $(src1), $(src1_files)) $(addprefix $(src2), $(src2_files))
objects := $(addprefix $(obj), $(src1_files:.c=.o)) $(addprefix $(obj), $(src2_files:.c=.o))
$(obj)%.o: src1/%.c
$(CC) $(CFLAGS) -c $< -o $@
$(obj)%.o: src2/%.c
$(CC) $(CFLAGS) -c $< -o $@
all: $(objects)
我在cygwin的bash
中进行了测试:
I tested in bash
on cygwin:
$ mkdir src1 src2 objects
$ touch src1/a.c src1/b.c src2/c.c src2/d.c
$ make
cc -c src1/a.c -o objects/a.o
cc -c src1/b.c -o objects/b.o
cc -c src2/c.c -o objects/c.o
cc -c src2/d.c -o objects/d.o
$
...而且有效.
(我省略了有关构建objects
目录的详细信息,只是手动创建的.)
(I left out the detail about building the objects
directory – just created it manually).
这篇关于Makefile将源文件从不同目录构建到同一对象目录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!