Environment in Make

Following description is based on linux/bash. It is easy to switch to other platforms/shells.

Set Environment

There are two ways to set environment variables

export MYVAR=myvalue

the command sets the environment variable in current shell, the variable keep valid until it is deleted or changed and will be passed to all child processes by default.

MYVAR=myvalue command

This sets the environment variable for the command only (and it will be inherited by that process. It won’t change current shell environment.

We use this perl script to show a process environment

$ cat env.pl
#! /usr/bin/env perl

my $en = shift || 'MYVAR';
my $ev = $ENV{$en};
$ev = '' unless defined($ev);
print "$en=$ev\n";

Here is the result

$ ./env.pl
MYVAR=
$ export MYVAR=hello
$ echo $MYVAR
hello
$ ./env.pl
MYVAR=hello
$ unset MYVAR
$ echo $MYVAR

$ ./env.pl
MYVAR=
$ MYVAR=Hello ./env.pl
MYVAR=Hello
$ echo $MYVAR

$

Set Make Variable

Make variable can be set by environment (by setting before make), by command line (by setting after make), or set inside make file.

  1. both environment and command set initial variable value
  2. inside setting override environment value (unless -e is set for make)
  3. command line setting always overrides makefile setting (in other words, makefile setting can’t change command line settings)

Here is a makefile

$(info init value CC=$(CC), CXX=$(CXX))

CC :=gcc
CXX :=g++

all:
        @echo CC=$(CC) CXX=$(CXX)

The execute result is

$ CC=hello make
init value CC=hello, CXX=g++
CC=gcc CXX=g++
$ CC=hello make -e
init value CC=hello, CXX=g++
CC=hello CXX=g++
$ make CC=hello
init value CC=hello, CXX=g++
CC=hello CXX=g++
$ CC=hello make CXX=world
init value CC=hello, CXX=world
CC=gcc CXX=world
$