如何在Makefile的先决条件中执行整数算术?

huangapple go评论43阅读模式
英文:

How to do integer arithmetic in Makefile prerequisites?

问题

%.x:<???>.y

GNU Make 似乎没有自带的整数算术功能,而且 shell 扩展($$(( ))$(shell ))似乎不能用于前提条件。

在 Makefile 中是否有方法来实现这一点,或者我应该使用一个外部脚本来生成这些依赖关系,然后让 Makefile 包含它们?

编辑:我的具体情况涉及包含财务交易的文件。每个文件(例如 2023.journal)代表了特定年份的交易,并包括一个开头声明(例如 2023_opening.journal),该声明基于前一年的结尾声明。这在 2023_opening.journal2022.journal 之间创建了一个依赖关系。

英文:

I have a file &lt;n&gt;.x and &lt;n-1&gt;.y and I want to create a dependency in my Makefile.
Manually I can write each case as follows:

2.x : 1.y
3.x : 2.y
4.x : 3.y
...

Now I would like to be able to write this more generically:

%.x : &lt;???&gt;.y

Gnu Make doesn't seem to have integer arithmetic on its own and shell expansions ($$(( )), $(shell ) don't seem to work for prerequisites.

Is there a way do this in the Makefile itself or should I use an external script that can generate these dependencies and let the Makefile include them?

Edit: My specific case is dealing with files containing financial transactions. Each file (e.g. 2023.journal) represents transactions for a specific year and includes an opening statement (e.g. 2023_opening.journal), which is based on the closing statement of the year before that. This create a dependency between 2023_opening.journal and 2022.journal.

答案1

得分: 1

使用GNU make:

.SECONDEXPANSION:
%.x: $$(shell expr $$* + 1).y

.SECONDEXPANSION 特殊目标之后的所有规则,其先决条件列表(仅限于列表)会被make处理两次:第一次是在make解析Makefile时,就像其他所有内容一样,第二次是当make需要检查目标的先决条件时。与第一阶段相反,在第二阶段中,自动变量被定义。

因此,在第一阶段之后,规则变为:

%.x: $(shell expr $* + 1).y

$* 是make的自动变量,它在模式规则中扩展为匹配%的部分。在你的情况下,它是与%匹配的部分。

然后,当make需要获取1.x的先决条件列表时,规则再次被处理,$(shell expr $* + 1).y被扩展,并逐步变成:

  1. 1.x: $(shell expr 1 + 1).y # $* --> 1
  2. 1.x: 2.y # $(shell expr 1 + 1) --> 2
英文:

With GNU make:

.SECONDEXPANSION:
%.x: $$(shell expr $$* + 1).y

All rules after the .SECONDEXPANSION special target have their list of prerequisites (and only that) processed twice by make: a first time, as everything else, when make parses the Makefile, plus a second time when make needs to check the prerequisites of a target. Contrary to the first phase, during the second phase the automatic variables are defined.

So, after the first phase the rule becomes:

%.x: $(shell expr $* + 1).y

$* is the make automatic variable that expands as the stem in pattern rules. In your case it is the part that matches the %.

And then, when make needs the list of prerequisites for 1.x, the rule is processed again, $(shell expr $* + 1).y is expanded, and becomes (step by step):

  1. 1.x: $(shell expr 1 + 1).y # $* --&gt; 1
  2. 1.x: 2.y # $(shell expr 1 + 1) --&gt; 2

huangapple
  • 本文由 发表于 2023年6月1日 21:22:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定