Makefile中%和*有什么区别 [英] What is the difference between % and * in a makefile

查看:778
本文介绍了Makefile中%和*有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GNU make手册没有擅长解释这一部分,我找不到解释,或者我无法推断其他地方的信息.

The GNU make manual does not excel at explaining this part, I could not find the explanation or I could not infer the information elsewhere.

我意识到%是一种通配符,但是在targetsdependenciescommands的上下文中%*有什么区别?我在哪里可以使用它,并且到处都具有相同的含义?

I realize % is a kind of wildcard, but what is the difference between % and * in the context of targets, dependencies and commands? Where can I use it and does it have the same meaning everywhere?

target: dependencies ...
    commands

推荐答案

通配符*用于简单地在当前目录中生成匹配文件的列表.模式替换字符%是当前可能存在或不存在的文件的占位符.

The wildcard character * is used to simply generate a list of matching files in the current directory. The pattern substitution character % is a placeholder for a file which may or may not exist at the moment.

要扩展通配符陷阱您已经发现的手册中的示例

To expand on the Wildcard pitfall example from the manual which you had already discovered,

objects = *.o

简单地为变量分配了相当无用的文字值*.o-一个目标文件,该文件可能依赖于一个字面意义为*.c的文件,该文件当然也不存在.这样您会得到一个错误和/或不稳定的行为.

simply assigns to the variable the rather useless literal value *.o -- an object file which presumably depends on a file named literally *.c which of course also does not exist. So you get an error, and/or erratic behavior.

正确的短语表达方式

objects := $(patsubst %.c,%.o,$(wildcard *.c))

make本身在这种情况下不执行通配符扩展,但是,当然,如果将字面值*.o传递给外壳,则在扩展发生时(如果存在匹配项),因此这可能很难调试. make 在规则目标中执行通配符扩展,因此您可以说

make itself performs no wildcard expansion in this context, but of course, if you pass the literal value *.o to the shell, that's when expansion happens (if there are matches) and so this can be slightly hard to debug. make will perform wildcard expansion in the target of a rule, so you can say

foo: *.o

并使其完全按照您的预期工作(前提是在评估此依赖项时保证所需文件已存在).

and have it work exactly like you intended (provided the required files are guaranteed to exist at the time this dependency is evaluated).

相比之下,您可以拥有一个带有模式占位符的规则,当make尝试查找可用于生成所需依赖项的配方时,该规则将以任何匹配的名称填充.有内置的规则,例如

By contrast, you can have a rule with a pattern placeholder, which gets filled in with any matching name as make tries to find a recipe which can be used to generate a required dependency. There are built-in rules like

%.o: %.c
        $(CC) $(CCFLAGS) $^ -o $@

(这里近似真实的东西)说:给与%.c匹配的文件,相应的文件%.o可以如下生成."在这里,%是一个占位符,可以用任何东西代替;因此,如果将其应用于现有文件foo.c,则说明如何生成foo.o.

(approximating the real thing here) which say "given a file matching %.c, the corresponding file %.o can be generated as follows." Here, the % is a placeholder which can be replaced by anything; so if it is applied against an existing file foo.c it says how foo.o can be generated.

您可以改写为说*匹配每个匹配文件,而%匹配任何匹配文件.

You could rephrase it to say * matches every matching file while % matches any matching file.

这篇关于Makefile中%和*有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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