Makefile 没有正确地为变量赋值

Makefile not assigning the value to variables properly

我正在尝试做类似的事情:

wt=$(sed -n ... file1) 
sed -i "s/temp/$(wt)/" file2

wt 是一个变量,它从 file1 获取它的值,我想用 wt 的值替换 file2 中的 "temp"。

sed 命令工作,因为我试图在终端中做同样的事情并且它工作,但是当我 运行 "make" 时,它给出的输出为:

wt=
sed -i "s/temp//" file2

我正在使用 GNU Make 4.3。

编辑:我试图在我的 Makefile 中的函数中执行此操作,如下所示:

define func
    wt=$(sed -n ... $(2)) 
    sed -i "s/temp/$(wt)/" $(1)
endef

按照同样的方式做:

$ cat data.txt 
temp

$ cat Makefile 
define func
wt=$$(echo $(2)); \
sed "s/temp/$$wt/" $(1)
endef

.PHONY: all

all:
    $(call func,data.txt,name)

$ make
wt=$(echo name); sed "s/temp/$wt/" data.txt
name

不会工作:

define func
wt=$$(echo $(2))
sed "s/temp/$$wt/" $(1)
endef

为什么?因为如果你这样做,食谱:

all:
    $(call func,data.txt,name)

make 扩展后变为:

all:
    wt=$(echo name)
    sed "s/temp/$wt/" data.txt

如您所知,配方的每一行都在其自己的 shell 中执行。

    wt=$(echo name) # `wt` is a shell variable in this shell
    sed "s/temp/$wt/" data.txt # `wt` is undefined in this shell

所以你需要配方来执行一行:

    wt=$(echo name); sed "s/temp/$wt/" data.txt # Same shell

或使用续行:

wt=$$(echo $(2)); \
sed "s/temp/$$wt/" $(1)

同样,你可以这样写:

define func
wt=$$(echo $(2)); sed "s/temp/$$wt/" $(1)
endef