gmake编译目录中的所有文件 [英] gmake compile all files in a directory
问题描述
我们需要一些C ++代码来创建一个make文件.每个.h和.C对都创建一个对象,然后将某些对象链接在一起以形成可执行文件.很标准的东西.
we have some C++ code that we need to create a make file in. Each .h and .C pair create an object and then some objects are linked together to form a executable. Pretty standard stuff.
此非gnu make命令仅将所有文件构建到目录中的对象中
This non-gnu make command just builds all the files into object in a directory
%.o:%.C
$(CC) $(CPFLAGS) -c $<
这是为每个%.C文件(即每个.C文件)建立一个相应的.o文件.
What this does is for each %.C file (ie every .C file) build a corresponding .o file.
有人知道如何使用gmake吗?
Does anybody know how to do this with gmake?
欢呼
标记
推荐答案
您所显示的语法在GNU make术语中称为模式规则,它构成了解决方案的基石.您所需要做的就是添加一种动态获取.C文件列表的方法.其他人展示了使用$(shell)
来执行此操作的解决方案,但这是不必要的效率低下.我建议您改用$(wildcard),这是一个GNU make内置函数,专门用于此目的:
The syntax you've shown is called a pattern rule in GNU make parlance, and it forms the corner stone of your solution. All you need is to add a way to get the list of .C files dynamically. Others have shown solutions that use $(shell)
to do this, but that's needlessly inefficient. I suggest you instead use $(wildcard), which is a GNU make built-in function designed for just this purpose:
SRCS = $(wildcard *.C)
OBJS = $(patsubst %.C,%.o,$(SRCS))
foo: $(OBJS)
$(CC) -o $@ $^
%.o: %.C
$(CC) $(CPFLAGS) -c $<
如果您正在寻找更简洁的方法,以下方法也将起作用:
If you are looking for something more concise, the following will work too:
foo: $(patsubst %.C,%.o,$(wildcard *.C))
这只是消除了变量,并利用了GNU make提供默认的%.o: %.C
模式规则以及将一组对象中的可执行文件链接在一起的默认规则这一事实.就我个人而言,我会使用更为冗长的版本,因为我发现它更易于阅读和维护,但各有千秋.
This just eliminates the variables and takes advantage of the fact that GNU make provides a default %.o: %.C
pattern rule, as well as a default rule for linking an executable together from a set of objects. Personally I would use the more verbose version as I find it easier to read and maintain, but to each their own.
希望有帮助,
埃里克·梅尔斯基
这篇关于gmake编译目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!