【问题标题】:how to use target specific variable in gnu make如何在 gnu make 中使用目标特定变量
【发布时间】:2014-04-11 01:49:12
【问题描述】:

我有一个像这样的makefile:

file1 = "path/to/some/file"
header="col1;col2;col3"

$(file1):
      some steps to create the file
call_perl_script:$(file1)
      ${perl} script.pl in=header

标头当前是硬编码的,它也在生成的 file1 中。我需要从 file1 中获取标题。不知怎的,我改变了它像

file1 = "path/to/some/file"

$(file1):
      some steps to create the file
      $(eval header="$(shell $(sed) -n "/^col1;col2;col3/Ip" $(file1))")
call_perl_script:$(file1)
      ${perl} script.pl in=$(header)

它工作正常,但想知道它是否是使用目标特定变量的正确方法。在与 eval 一起使用之前,标头不会传递其值。 此外,如果我在 call_perl_script 目标中打印 $(header),它会正确打印,但如果我使用“if”条件检查变量是否为空并设置默认值,那么它就不起作用。它在“if”块中设置 header 的值,而不考虑“sed”输出中 header 中的值。

call_perl_script:$(file1)
${echo} $(header)
ifeq "$(header)" ""
      $(eval header="col1;col2;col3")
endif
      ${perl} script.pl in=$(header)

【问题讨论】:

    标签: build makefile gnu-make


    【解决方案1】:

    我认为特定于目标的变量在这里不会对您有所帮助,因为它们通常是静态的。例如,如果您需要对一个特定的 C 文件消除一种类型的警告,您可以添加类似 foo.o: CFLAGS+=-Whatever 的规则。

    您遇到的问题是 $(eval header=...) 仅在创建 $(file1) 时执行。如果它已经存在,则不会重建目标,也不会设置 header

    在 Makefile 中执行此操作的一种更自然的方法是将标头保存到单独的文件中。这样,只要$(file) 发生变化,它就会自动重新生成:

    .DELETE_ON_ERROR:
    
    file = foo.txt
    
    call_perl_script: $(file) $(file).header
            echo perl script.pl in="$(shell cat $(file).header)"
    
    $(file):
            echo "col1;col2;col3;$$(head -c1 /dev/random)" > $(file)
    
    %.header: %
            sed -n '/^col1;col2;col3/p' $< > $@
    
    clean::
            rm -f $(file)
            rm -f *.header
    

    导致:

    echo "col1;col2;col3;$(head -c1 /dev/random)" > foo.txt
    sed -n '/^col1;col2;col3/p' foo.txt > foo.txt.header
    perl script.pl in="col1;col2;col3;?"
    

    但这仍然有点麻烦,因此为了长期可维护性,您可能需要考虑更新 script.pl 以解析出标头本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2013-12-19
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      相关资源
      最近更新 更多