Search code examples
makefileenvironment-variablesposix

Export variable for a target in POSIX Make


In GNU Make you can export a variable for a target:

foo: export X=42
foo:
    echo $$X
    # Call several more commands that use $X.

Is there a way to do this in portable POSIX Make? So far, I've found two ways. The first is to basically merge all commands into one:

foo:
    export X=42; \
        echo $$X; \
        # Call several more commands that use $X.

This is bad because now everything is bundled together. The second is to call $(MAKE):

foo:
    $(MAKE) foo_ X=42
foo_:
    echo $$X
    # Call several more commands that use $X.

But this has an extra call to make again. Is there a better way?


Solution

  • The simplest solution is probably to set the variable on the command line by invoking make with:

    make X=42
    

    This way:

    1. The make X variable is defined and set to 42, even if it is set to another value in the Makefile.
    2. The shell environment variable X is defined and set to 42 for all recipes.

    If you cannot use this (for instance because it is make that computes the value) the recursive make solution is probably the best option:

    ifeq ($(X),)
    X := <some-make-magic>
    
    all:
        $(MAKE) X=$(X) all
    else
    all:
        <recipe-that-uses-X-environment-variable>
    endif