Archive

Posts Tagged ‘Makefile’

Reading environment variables from a file into a Makefile

January 30, 2019 Leave a comment

Problem:
You have a bunch of environment variables that are explicitly set at the beginning of a Makefile. These variables are then used in various recipes in the Makefile. The issue was that when a developer runs the Makefile, these environment variables overwrite their local settings.

Solution:
One option is to move the environment variables out of the Makefile and use include to add them back. So the developer can use whatever values they have in their current setup as long as the names are the same.

# Makefile

foo=FOO1
bar=BAR1
baz=BAZ1

export foo
export bar
export baz

.PHONY:  target1 target2 target3

target1:
    @echo $(foo)

target2:
    @echo $(bar)

target3:
    @echo $(baz)

After splitting it up.

# .env file
foo=FOO1
bar=BAR1
baz=BAZ1

export foo
export bar
export baz
# Makefile
include .env

.PHONY:  target1 target2 target3

target1:
    @echo $(foo)

target2:
    @echo $(bar)

target3:
    @echo $(baz)

The problem with this approach is that the .env file needs to exist everywhere it will run. If you have some CI/CD setup that may not be the case. Instead have the Makefile as below and have the ENV vars set up the usual way you would in your CI/CD setup. On the local machine one can simply run $ source .env before running $ make to get things to work.

# Makefile
.PHONY:  target1 target2 target3

target1:
    @echo $(foo)

target2:
    @echo $(bar)

target3:
    @echo $(baz)

Source:
https://stackoverflow.com/questions/39005789/reading-makefile-variables-from-bash-script

Advertisements
Categories: bash Tags:

GNU Makefile setting env variables

January 12, 2019 Leave a comment

Problem:
Exporting env variables in Makefiles. The issue was that the environment variables were not visible across different targets. I needed the same env vars to be seen in both target1 and target2 below.

Solution:
Export the variables outside the target, eg at the top of the file.

VALUE1="myvalue1"
VALUE2="myvalue2"

export VALUE1
export VALUE2

target1:
    echo $VALUE1

target2:
    echo $VALUE2

Source:
https://stackoverflow.com/questions/2826029/passing-additional-variables-from-command-line-to-make
https://www.linuxquestions.org/questions/programming-9/exporting-makefile-variables-to-%24-shell-environment-807422/

Categories: bash, Interesting Tags: ,