Makefile How to use variables defined in a config file

eye-catch Other techs

It took me a while to clarify how to import variables from a config file.

We have makefile.env and define environment variables there.

VM_HOST=192.168.100.1

This variable needs to be used in a makefile.

echo:
    @echo "HOST: " $(VM_HOST)
Sponsored links

Why is it necessary in the first place

Assume that another developer in the same project wants to connect to a VM to copy files by Make command for example.

The IP address could be different on each laptop.

I didn’t want to write the IP address to the makefile because the file is handled as a changed file by Git if another developer changes the setting in the makefile.

If we have a setting file that is ignored by .gitignore file, we don’t have to worry about an accidental commit.

Sponsored links

Solutions

Add include

The first solution is to add include <path to the config file>.

include makefile.env
# 192.168.100.1, 192.168.100.1,
echo:
    @echo $(VM_HOST), ${VM_HOST}, $${VM_HOST}

# 192.168.100.1, 192.168.100.1, 
echo2:
    @echo "$(VM_HOST), ${VM_HOST}, $${VM_HOST}"

# 192.168.100.1, 192.168.100.1, ${VM_HOST}
echo3:
    @echo '$(VM_HOST), ${VM_HOST}, $${VM_HOST}'

The environment variable can be accessed by $(VM_HOST) or ${VM_HOST}.

The environment variable is handled as a Make variable. Use a single dollar sign in this case.

Read the config file on the same line

The second solution is to read the file on the same line.

# , , 192.168.100.1
echo:
    @. ./makefile.env && echo $(VM_HOST), ${VM_HOST}, $${VM_HOST}

# , , 192.168.100.1, 
echo2:
    @. ./makefile.env && echo "$(VM_HOST), ${VM_HOST}, $${VM_HOST}, $$(VM_HOST)"

# , , $${VM_HOST}, $(VM_HOST)
echo3:
    @. ./makefile.env && echo '$(VM_HOST), ${VM_HOST}, $${VM_HOST}, $$(VM_HOST)'

The environment variable can be accessed by $${VM_HOST}. Parentheses can’t be used for this.

The environment is handled as a Shell variable. Use two dollar sign in this case.

Be aware that if $${VM_HOST} is used in single quotes, it is handled as a string

Shell variable becomes empty if config file is read on another line

Don’t use the variable on a different line. It can’t be used in this case.

# 192.168.56.102
# HOST: 
echo:
    @. ./makefile.env && echo $${VM_HOST}
    @echo "HOST: $${VM_HOST}"

Comments

Copied title and URL