如何在一个Makefile中生成多个可执行文件? [英] How to generate multiple executable files in one Makefile?
问题描述
我的目录包含2
个源文件:a.c
和b.c
.我想从a.c
生成可执行文件a
,从b.c
生成b
.现在,我只能找出一种编写Makefile的方法:
My directory contains 2
source files: a.c
and b.c
. I want to generate executable file a
from a.c
and b
from b.c
. Now I can only figure out one method to write Makefile:
all:
gcc -o a a.c
gcc -o b b.c
似乎有点尴尬,这是更好的方法吗?
It seems a little awkward, is it better method?
推荐答案
答案很好,但我仍然认为您需要对make
的工作方式有一些了解:
The answers are fine, still I think you need some insight in how make
works:
make
的基本功能是根据需要从输入文件创建输出文件. make
通过比较时间戳来确定什么是必要的:如果任何输入文件比从其创建的输出文件新,则执行该输出文件的配方.
The basic functionality of make
is to create output files from input files if necessary. make
decides what is necessary by comparing timestamps: If any input file is newer than an output file created from it, the recipe for this output file is executed.
这意味着仅使用一条名为all
的规则,该规则就会一直执行 (除非您碰巧有一个最近的文件实际上称为 all
,为防止这种情况,您必须将all
列为.PHONY
目标,即实际上并未创建文件的目标).您原始的Makefile相当于一个简单的Shell脚本,因此没有正确使用make
.
This means with just a rule named all
, this rule is always executed (except when you happen to have a recent file actually called all
-- to prevent this behavior, you have to list all
as a .PHONY
target, that is one that doesn't actually create a file). Your original Makefile is equivalent to a simple shell script, so it doesn't use make
properly.
Makefile的最小正确"版本应如下所示:
The minimal "correct" version of your Makefile should look like this:
all: a b
a: a.c
gcc -o a a.c
b: b.c
gcc -o b b.c
.PHONY: all
因此,all
是"phony",并且取决于a
和b
. a
仅在a.c
更改时重建,b
仅在b.c
更改时重建.
So, all
is "phony" and depends on a
and b
. a
is only rebuilt when a.c
changed, b
is only rebuilt when b.c
changed.
在真实的项目中,您的程序可能不仅仅是由一个源文件构成的,在这种情况下,您可以真正利用make
的优势:让它构建目标文件的翻译单位,因此实际上只有重建的 parts 会被重建.对于您的小例子来说,这太过分了,但是例如看起来像这样:
In a real project, your programs are probably made from more than just one source file and in this case, you can really take advantage of make
: Have it build object files of your translation units, so only the parts that changed are actually rebuilt. It's overkill for your tiny example, but could e.g. look like this:
a_OBJS:= a.o
b_OBJS:= b.o
all: a b
a: $(a_OBJS)
gcc -o$@ $^
b: $(b_OBJS)
gcc -o$@ $^
%.o: %.c
gcc -c -o$@ $<
clean:
rm -f *.o
.PHONY: all clean
您只需要向a_OBJS
和b_OBJS
添加更多目标文件,以在您的构建中包括新的翻译单元. 样式规则 %.o: %.c
将匹配它们.还有很多发现,我建议从 GNU make manual .
You would just have to add more object files to a_OBJS
and b_OBJS
to include new translation units in your build. The pattern rule %.o: %.c
will match them. There's a lot more to discover, I suggest starting with the GNU make manual.
这篇关于如何在一个Makefile中生成多个可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!