如何在一个Makefile中生成多个可执行文件? [英] How to generate multiple executable files in one Makefile?

查看:648
本文介绍了如何在一个Makefile中生成多个可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目录包含2个源文件:a.cb.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",并且取决于ab. 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_OBJSb_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆