Noeud:Environment Variables, Noeud « Up »:Invoking Make



Environment Variables

In addition to having a provision for overriding the values of Make variables at build time, Make also provides for supplying default values for variables that are not otherwise assigned. The mechanism for enabling this feature is simply through the UNIX environment. If you are using a bourne compatible shell1, variables are exported to the environment using the export keyword, like this:

     $ prefix=$HOME/test
     $ export prefix
     

With the prefix shell variable exported into the environment, it can be referred to from a Makefile with $(prefix), just like any other Make variable. However, it is only a default value, so it won't be seen if there is a declaration of prefix within the Makefile, or indeed if you override it from the command line as described in the last section.

GNU Make will allow you to force the Makefile to prefer settings from the environment over the variable declarations in the file if you specify the -e option when you invoke make. None of this is as complicated as it sounds - take the following Makefile fragment:

     includedir      = $(prefix)/include
     include_HEADERS = m4module.h error.h hash.h system.h
     ...
     install-HEADERS: $(include_HEADERS)
             @test -d $(includedir) || \
               { echo mkdir $(includedir); mkdir $(includedir); }
             @for p in $(include_HEADERS); do \
               echo cp $$p $(includedir)/$$p; \
               cp $$p $(includedir)/$$p; \
             done
     
     Example 5.32: Precedence of Make variable declarations
     

For this particular Makefile we can override the value of includedir like this:

     $ make -n includedir='$(HOME)/include'
     mkdir /home/gary/include
     cp m4module.h /home/gary/include/m4module.h
     ...
     

Notice that I set the override value of includedir to reference the variable $(HOME), and this was defaulted from my shell environment, since there is no declaration for HOME either in the Makefile or in the command line invocation.

However, there would be no point in setting includedir in the shell as an environment variable, since whatever default value was set, it would be superceded by the variable delaration at line 1 of Makefile. Unless, we use the -e option to make:

     $ prefix=/usr/local
     $ export prefix
     $ make -n -e
     cp m4module.h /usr/local/include/m4module.h
     cp error.h /usr/local/include/error.h
     ...
     

Notes de bas de page

  1. For example GNU bash, ksh, zsh, sh5 are all based on Steve Bourne's original UNIX shell.