Share variables between makefiles

You can create another file, for instance Makefile.variable where those shared variables are defined and include the file using

include $(PATHTOSHAREDMAKEFILE)/Makefile.variable

Look at the include manual for more information


You can pass the variable on the command-line:

test:
    make -C test PACKAGES="$(PACKAGES)"

Note that it's not possible to go the other way around though. If the test/Makefile changes a variable, then these changes can't come back to the calling makefile.


If you want to add to the PACKAGES variable in the main makefile, you will have to refactor your build system to include sub-makefiles instead. So the main makefile sets everything up, then includes (using the include directive available in most make implementations) the sub-makefiles which adds specific targets local to them, as well as alter/add variables.

For example, lets say you have two test directories, test_foo and test_bar, you could have a variable containing the test targets, lets call it TEST_TARGETS. Each makefile in the test_* folder adds its local and unique target to the global variable and the main makefile can then run them.

Something like this:

Main makefile:

# Start empty
TEST_TARGETS =

include test_foo/Makefile
include test_bar/Makefile

test:
    for target in "$(TEST_TARGETS)"; do \
        $(MAKE) $(target); \
    done

test_foo/Makefile:

TEST_TARGETS += test_foo

test_foo:
    # Do some foo testing

test_bar/Makefile:

TEST_TARGETS += test_bar

test_bar:
    # Do some bar testing

Tags:

Makefile