首页 > 解决方案 > Makefile没有正确地将值分配给变量

问题描述

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

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

标签: bashvariablessedmakefilegnu-make

解决方案


以与此相同的方式执行此操作:

$ 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

推荐阅读