【问题标题】:resolve Makefile wildcard % inside shell function在 shell 函数中解析 Makefile 通配符 %
【发布时间】:2010-09-02 17:10:58
【问题描述】:

在调用 shell 函数之前,make 似乎没有解析通配符 %,在这种情况下:

%.exe: $(shell cat %.txt)
    gcc $? -o $@

如果我在 shell 上输入这个:

$ make test.exe

shell 抱怨它找不到“%.txt”,但我希望它会找到“test.txt”。

有没有办法解决这个问题?

谢谢!

【问题讨论】:

  • 你能澄清一下你想用这条规则完成什么吗?
  • 对于每个可执行文件 X,都有一个文件 X.txt 列出了它的所有源依赖项。我希望“make”将该文件的内容作为目标依赖项。
  • $(shell ...) 的扩展很早就发生了;你的错误发生在 make 甚至开始查看目标之前。请按照以下建议阅读 GNU Make 文档中的“二次扩展”章节。

标签: shell makefile wildcard


【解决方案1】:

您可以使用 GNU make 的二次扩展功能:

$ cat Makefile
all : x.exe
.PHONY: all
.SECONDEXPANSION:
%.exe: $$(shell cat $$(basename $$(@F)).txt)
    @echo "$@ depends on $^"

$ cat x.txt 
a
b
c

$ touch a b c

$ make
x.exe depends on a b c

【讨论】:

    【解决方案2】:

    使foo.txt 包含foo.exe 的依赖项,格式为Makefile

    foo.exe: foo.o bar.o baz.o
    

    然后在您的Makefile 中使用include 行:

    include foo.txt
    

    最后,更新你的模式规则:

    %.exe:
        gcc -o $@ $^
    

    【讨论】:

    • 老实说,我只会使用像 automake 这样的生成器。它省去了很多这样的麻烦,而且结果是可移植的。
    • 按什么指标可移植? automake 的输出几乎适用于任何 POSIX make
    【解决方案3】:

    我认为您正在尝试这样做:

    .SUFFIXES: .exe .txt
    .txt.exe:
            gcc $? -o $@
    

    【讨论】:

    • 不,他不是。 .txt 文件命名了 .exe 文件的所有依赖项。
    • 啊!在这种情况下,他应该将依赖项放在 Makefile 而不是 .txt 文件中。
    【解决方案4】:

    嗯,从外部文件加载(动态生成)依赖项的常用方法是使用 include。 IE。您可以修复您的示例,您可以在 %.txt 文件生成期间添加目标。在 Makefile 中你可以这样写:

    DEPS = $(OBJS:.o=.txt)
    
    -include $(DEPS)
    

    顺便说一句,这些依赖文件通常使用的后缀是%.d。

    关注web site shows an intelligent approach to integrate the dependency generation in your Makefile. 即然后根据需要生成和更新依赖文件。不需要“make deps”步骤或类似的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多