代码之家  ›  专栏  ›  技术社区  ›  Pablo

makefile:在目标命令行中分配函数变量

  •  1
  • Pablo  · 技术社区  · 14 年前

    我需要 xpi_hash 仅当决定执行更新目标的命令时才分配的变量。然后我将这个变量用作环境、导出等。

    如果我把它放在规则之外,它将首先被扩展,在 $(xpi) 目标被调用,因此将找不到该文件。

    substitute := perl -p -e 's/@([^@]+)@/$$ENV{$$1} bla bla...
    
    export xpi_hash
    
    .PHONY: dirs substitute update
    
    update: $(xpi) $(target_update_rdf) 
        xpi_hash   := $(shell sha1sum $(xpi) | grep -Eow '^[^ ]+')
        @echo "Updating..."
    
    $(target_update_rdf): $(update_rdf)
        $(substitute) $< > $@
    

    当然,上面的内容是不正确的,因为对于命令部分,shell是被表示的。所以,也许提出这个问题的另一种方法是-如何将变量作为命令输出?

    2 回复  |  直到 14 年前
        1
  •  1
  •   Scott Wales    14 年前

    我不知道你到底在找什么,你打算怎么用 xpi_hash ?如果每次使用变量时都要获取当前哈希,请使用 = 指定变量而不是 := ,例如

    xpi_hash=$(shell sha1sum $(xpi) | grep -Eow '^[^ ]+')
    update:$(xpi) $(target_update_rdf)
        @echo $(xpi_hash)
    

    将打印的哈希 xpi 更新后。

    对于中的变量 make section 6.2 手册的。简而言之“:=”将展开右侧的变量,“=”将保留变量以便稍后展开。

    我的评论中修改过的命令( substitute = xpi_hash="$(xpi_hash)" perl -p -e 's/@([^@]+)@/$$ENV{$$1}...' )将扩展到等价于

    $(substitute)
    xpi_hash="$(xpi_hash)" perl -p -e 's/@([^@]+)@/$$ENV{$$1}...'
    xpi_hash="`sha1sum $(xpi) | grep -Eow '^[^ ]+'`" perl -p -e 's/@([^@]+)@/$$ENV{$$1}...'
    xpi_hash="`sha1sum xpi_expansion | grep -Eow '^[^ ]+'`" perl -p -e 's/@([^@]+)@/$$ENV{$$1}...'
    

    这个 xpi_hash="..." 语法是在bash子shell中定义一个变量,而不是在make中使用该变量。

        2
  •  1
  •   Beta    14 年前

    只要 substitute 必须使用 xpi_hash ,使xpi_hash成为目标特定变量:

    $(target_update_rdf): xpi_hash = $(shell ...)
    $(target_update_rdf): $(update_rdf)
        $(substitute) $< > $@
    

    如果其他Perl脚本需要 XPIH散列 ,如果要导出它,则会出现问题,因为在规则的子shell中分配的变量无法(很容易)进行通信。但是你可以把它存储在一个文件里 include 它:

    xpi_hash_file: $(xpi)
        rm -f $@
        echo xpi_hash = $(shell...) > $@
    
    -include xpi_hash_file