【问题标题】:Evaluating a dynamic macro multiple times in a Makefile在 Makefile 中多次评估动态宏
【发布时间】:2021-11-12 23:11:22
【问题描述】:

我有一个用例,我需要在规则中多次运行相同的命令。但是,命令参数需要根据另一个命令的返回值进行更改。我发现可以使用$(call foo_exec) 从规则中调用宏,这很棒。但是,请考虑以下简化代码:

define foo_exec
        @echo $(if $(filter sylvester,$(shell cat cats.txt)),Found Sylvester!,No Sylvester found!)
endef

build:
        $(call foo_exec)
        @echo sylvester > cats.txt
        $(call foo_exec)

如果我运行make build,我会得到以下输出:

cat: cats.txt: No such file or directory
cat: cats.txt: No such file or directory
No Sylvester found!
No Sylvester found!

它肯定写了cats.txt,但是,不知何故,在创建该文件之前,宏似乎只被评估了一次。

另外,在我的真实代码中,在该宏中创建变量会很有好处,但我似乎也无法完成这项工作。以下代码:

define foo_exec
        MESSAGE := $(if $(filter sylvester,$(shell cat cats.txt)),Found Sylvester!,No Sylvester found!)
        @echo $(MESSAGE)
endef

build:
        $(call foo_exec)
        @echo sylvester > cats.txt
        $(call foo_exec)

产生这个输出:

cat: cats.txt: No such file or directory
cat: cats.txt: No such file or directory
MESSAGE := No Sylvester found!
/bin/sh: MESSAGE: command not found
make: *** [build] Error 127

此时,我开始觉得宏可能不是实现所需功能的正确方法,但我不确定如何去做并避免重复大量代码。欢迎提出任何建议!

【问题讨论】:

    标签: shell makefile


    【解决方案1】:

    以下作品

    define foo_exec
            @if egrep -s -q sylvester cats.txt; then echo "Found Sylvester"; else echo "No Sylvester found!"; fi
    endef
    
    build:
            $(call foo_exec)
            @echo sylvester > cats.txt
            $(call foo_exec)
    

    有了这个输出:

    $ make build
    No Sylvester found!
    Found Sylvester
    

    问题是宏在build 配方启动时展开。因此,我们不希望宏扩展检查cats.txt 文件的存在。相反,我们希望宏生成执行检查的 bash 代码

    我可能解释得不是很好!

    【讨论】:

    • 感谢亚伦!我对它为什么这样做的直觉是相似的。您的内联 bash 解决方案还可以,但我想知道从可维护性的角度来看这是否是正确的方法,特别是如果它最终会包含更复杂的条件。不知何故,感觉就像 make 打算提供自己的替代结构,这样就不必依赖内联 bash,但我不知道如何让他们做我想做的事 :)
    • > 不知何故,感觉就像 make 打算提供自己的替代构造,不完全是,Make 构造被设计为在不同的时间运行,所以我认为它们没有意图被视为完美的替代品。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多