Next: , Previous: , Up: Portable Make Programming   [Contents][Index]


12.7 make macro=value and Submakes

A command-line variable definition such as foo=bar overrides any definition of foo in a makefile. Some make implementations (such as GNU make) propagate this override to subsidiary invocations of make. Some other implementations do not pass the substitution along to submakes.

$ cat Makefile
foo = foo
one:
        @echo $(foo)
        $(MAKE) two
two:
        @echo $(foo)
$ make foo=bar            # GNU make 3.79.1
bar
make two
make[1]: Entering directory `/home/adl'
bar
make[1]: Leaving directory `/home/adl'
$ pmake foo=bar           # BSD make
bar
pmake two
foo

You have a few possibilities if you do want the foo=bar override to propagate to submakes. One is to use the -e option, which causes all environment variables to have precedence over the makefile macro definitions, and declare foo as an environment variable:

$ env foo=bar make -e

The -e option is propagated to submakes automatically, and since the environment is inherited between make invocations, the foo macro is overridden in submakes as expected.

This syntax (foo=bar make -e) is portable only when used outside of a makefile, for instance from a script or from the command line. When run inside a make rule, GNU make 3.80 and prior versions forget to propagate the -e option to submakes.

Moreover, using -e could have unexpected side effects if your environment contains some other macros usually defined by the makefile. (See also the note about make -e and SHELL below.)

If you can foresee all macros that a user might want to override, then you can propagate them to submakes manually, from your makefile:

foo = foo
one:
        @echo $(foo)
        $(MAKE) foo=$(foo) two
two:
        @echo $(foo)

Another way to propagate a variable to submakes in a portable way is to expand an extra variable in every invocation of ‘$(MAKE)’ within your makefile:

foo = foo
one:
        @echo $(foo)
        $(MAKE) $(SUBMAKEFLAGS) two
two:
        @echo $(foo)

Users must be aware that this technique is in use to take advantage of it, e.g. with make foo=bar SUBMAKEFLAGS='foo=bar', but it allows any macro to be overridden. Makefiles generated by automake use this technique, expanding $(AM_MAKEFLAGS) on the command lines of submakes (see Automake in GNU Automake).


Next: The Make Macro MAKEFLAGS, Previous: Long Lines in Makefiles, Up: Portable Make Programming   [Contents][Index]