如何在 Makefile 中使用变量列表作为目标?
假设我正在编写一个 makefile,并且顶部有以下变量声明:
FILES = file1.cpp file2.cpp file3.cpp
现在假设我想使用特殊命令来编译每个变量,而不像这样指定每个目标:
file1.o : file1.cpp
custom_command file1.cpp
file2.o : file2.cpp
custom_command file2.cpp
file3.o : file3.cpp
custom_command file3.cpp
有没有更好的方法使用 $(FILES)
我在上面声明的变量?
像这样的东西:
$(FILES:.cpp=.o) : $(FILES)
custom_command $(FILES)
...只需对 $(FILES)
变量中的每个文件执行此操作。
Suppose I am working on a makefile and I have the following variable declaration at the top:
FILES = file1.cpp file2.cpp file3.cpp
Now suppose I want to compile each of those with a special command without specifying each target like this:
file1.o : file1.cpp
custom_command file1.cpp
file2.o : file2.cpp
custom_command file2.cpp
file3.o : file3.cpp
custom_command file3.cpp
Is there a better way to do this using the $(FILES)
variable I declared above?
Something like:
$(FILES:.cpp=.o) : $(FILES)
custom_command $(FILES)
...only it needs to do this for each file in the $(FILES)
variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。有一些所谓的模式规则。一个例子是最容易理解的:(
请记住,Makefiles 需要选项卡)。该规则描述了如何从 cpp 文件创建目标文件。
如果您不需要如此广泛的规则,则可以使用所谓的静态模式:
这是关于 静态模式规则 和 模式规则。
Yes. There are what are known as pattern rules. An example is the easiest to understand:
(remember that Makefiles require tabs). This rule describes how to make an object file from a cpp file.
If you do not want such a broad rule, you can use what are called static patterns:
Here's the section on static pattern rules and pattern rules in the GNU Make manual.
您可以按照以下方式执行此操作:
但您必须记住依赖项是完整的 - 它假设
ao
依赖于bc
作为好吧,情况可能并非如此。您可能需要的是关于如何将一种文件类型转换为另一种文件类型的单个规则:
.co
就是这样一条规则,它规定了要运行哪些命令来转换.c
> 文件转换为.o
文件。在实际命令中,$@
替换为特定目标,$<
替换为第一个先决条件的名称。您还可以使用许多其他自动变量,可以使用
info make
查找它们,或者如果您不会的话,可以查找一本关于make
的好书拥有可用的info
内容。You can do that, as per the following:
but you have to remember that the dependencies are complete - it assumes that
a.o
depends onb.c
as well which is probably not the case.What you're probably after is a single rule on how to turn one file type into another:
.c.o
is such a rule which states what commands to run to turn a.c
file into a.o
file. In the actual command,$@
is replaced with the specific target and$<
is replaced with the name of the first prerequisite.There are many other automatic variables you can use, look them up with
info make
or look for a good book onmake
if you don't have theinfo
stuff available.虽然
$<
不太可移植(IIRC,bsdmake 具有$^
的含义,并且$<
完全交换为 gmake 使用的内容),这是.co
的默认配方,在任一实现中都有效。Though
$<
isn't quite portable (IIRC, bsdmake has the meaning of$^
and$<
exactly swapped to what gmake uses), this is the default recipe for.c.o
that would be in effect in either implementation.