在shell脚本中使用makefile变量而不运行make

时间:2021-09-12 23:36:46

We have a big make file that defines a lot of useful variables, like TEST_ENV. I'd like to make a shell script that lives in the same directory, and was wondering if there is any way to use the variables defined in the Makefile from the shell script. The variables I'm interested in are all defined like this

我们有一个很大的make文件,它定义了很多有用的变量,比如TEST_ENV。我想创建一个位于同一目录的shell脚本,我想知道是否有任何方法可以使用shell脚本中在Makefile中定义的变量。我感兴趣的变量都是这样定义的

TEST_ENV := PATH=/path/to/thing \
            CONFDIR=/another/path

or

host_installdir = /still/a/path

The reason I want the script use the Makefile is so that if the variable ever needs to be changed inside the Makefile, the shell script won't get out of date.

我希望脚本使用Makefile的原因是,如果需要在Makefile中修改变量,shell脚本就不会过时。

I found this related question, but was hoping there might be a way to do this without having to run make first.

我发现了这个相关的问题,但是希望有一种方法可以不用先运行make。

I considered the possibility of somehow using grep on the Makefile, but some of the variables are defined across multiple lines, which makes it tricky and breakable (for instance, if I do grep -A 3 for a variable defined across 3 lines, what if a 4th line is added later?).

我考虑了在Makefile中使用grep的可能性,但是有些变量是跨多行定义的,这使得它变得很棘手和容易被破坏(例如,如果我对一个跨三行定义的变量执行grep - 3,那么如果在后面添加第4行呢?)

2 个解决方案

#1


1  

TEST_ENV=$(make -qp | awk -F' = ' '$1=="TEST_ENV" {print $2}')

I'm sure there are edge cases this doesn't handle, but it's a decent start. Rudimentary testing shows this handles multi-line variables.

我肯定有一些边缘情况不能处理,但这是一个不错的开始。初步测试显示,这可以处理多行变量。

#2


2  

You could use (a modified version of) the print-% target from Makefile hacks: print the value of any variable in your makefile to let you query it for values.

您可以使用(修改后的)Makefile hacks中的print-%目标:打印Makefile中任何变量的值,让您查询它的值。

print-%:
        @echo '$(subst ','\'',$($*))'

#1


1  

TEST_ENV=$(make -qp | awk -F' = ' '$1=="TEST_ENV" {print $2}')

I'm sure there are edge cases this doesn't handle, but it's a decent start. Rudimentary testing shows this handles multi-line variables.

我肯定有一些边缘情况不能处理,但这是一个不错的开始。初步测试显示,这可以处理多行变量。

#2


2  

You could use (a modified version of) the print-% target from Makefile hacks: print the value of any variable in your makefile to let you query it for values.

您可以使用(修改后的)Makefile hacks中的print-%目标:打印Makefile中任何变量的值,让您查询它的值。

print-%:
        @echo '$(subst ','\'',$($*))'