Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Define make variable at rule execution time

In my GNUmakefile, I would like to have a rule that uses a temporary directory. For example:

out.tar: TMP := $(shell mktemp -d)
        echo hi $(TMP)/hi.txt
        tar -C $(TMP) cf $@ .
        rm -rf $(TMP)

As written, the above rule creates the temporary directory at the time that the rule is parsed. This means that, even I don't make out.tar all the time, many temporary directories get created. I would like to avoid my /tmp being littered with unused temporary directories.

Is there a way to cause the variable to only be defined when the rule is fired, as opposed to whenever it is defined?

My main thought is to dump the mktemp and tar into a shell script but that seems somewhat unsightly.

Answer*

Cancel
4
  • Just as a reminder, GNU make has a syntax for order-only prerequisites which may be necessary to complement this approach.
    – anol
    Commented Jun 5, 2014 at 19:24
  • 21
    Be careful with this solution! ruleA: TMP = $(shell mktemp -d testruleA_XXXX) and ruleB: TMP = $(shell mktemp -d testruleB_XXXX) will happen when the Makefile is first evaluated. In other words, ruleA: TMP = $(shell ... happens sooner than you think. While this might work for this particular case, this method will cause problems for some sequential operations. Commented Jun 11, 2015 at 2:55
  • 1
    That's not my experience - rule-local variables are expanded only when the particular rule is requested (either explicitly or as dependcy)
    – Zaar Hai
    Commented Oct 23, 2020 at 9:54
  • 1
    This should still work if you do ruleA: private TMP = .... See target-specific variables. Commented Jan 22, 2021 at 0:23