makefile - 在 makefile 中设置环境变量

标签 makefile environment-variables gnu-make

我有一个像这样的makefile:

setup:
  setenv var1 "$(var1)"; \
  setenv var2 "$(var2)";

task1: setup
  source task1.csh

task2: setup
  source task2.csh

我使用以下命令调用 makefile:

make var1=value1 var2=value2 task1

我希望环境变量 var1var2task1.cshtask2.csh 中可见,但我无法这样做,除非我将 makefile 更改为:

task1:
  setenv var1 "$(var1)"; \
  setenv var2 "$(var2)"; \
  source task1.csh

task2:
  setenv var1 "$(var1)"; \
  setenv var2 "$(var2)"; \
  source task2.csh

为什么第一种方法不起作用以及如何修复它?

最佳答案

这不起作用,因为 makefile 规则中的每一行都在其自己的 shell 实例中运行。

来自GNU make manual :

When it is time to execute recipes to update a target, they are executed by invoking a new sub-shell for each line of the recipe, unless the .ONESHELL special target is in effect (see Using One Shell) (In practice, make may take shortcuts that do not affect the results.)

Please note: this implies that setting shell variables and invoking shell commands such as cd that set a context local to each process will not affect the following lines in the recipe.2 If you want to use cd to affect the next statement, put both statements in a single recipe line

因此,您可以按照列出的方式进行操作,或者可以从 make 导出变量,它们已经位于子 shell 的环境中。

export var1 = value1
export var1 = value2

任务1: 源task1.csh

任务2: 源task2.csh

顺便说一句,为什么您要获取这些脚本而不是直接运行它们(./task1.sh)?

(我假设您在 makefile 中设置了 SHELL = csh 或类似内容,以使其完全正常工作。)

关于makefile - 在 makefile 中设置环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27282660/

相关文章:

makefile - 如何导入 yaml 文件以在 gnu make 文件中使用它?

makefile - 在简单扩展的变量之前

c++ - 在 Visual Studio 2005 中调试时显示环境变量?

build - 如何使用 SCons 在不同环境中构建?

makefile - 如何在 qmake 生成的 Makefile 中添加自定义目标?

docker - 惯用的 Makefile 和命令参数

c++ - 从 cmake 执行 make

linux - 如何修复linux下编译错误

linux - 插入环境变量

linux - 如何让 android 在 ubuntu 14.04 上运行得更快?