JonMorehouse
JonMorehouse

Reputation: 1383

Share variables between makefiles

I have a directory structure where I want one main makefile in my main folder, and then another makefile in both my test and src folder.

In my main makefile, I have directives for both test / all that call the individual folder makefiles. I'm trying to declare variables in my main makefile and have them accessible to those other folders.

For instance in my main Makefile

PACKAGES = jansson mysql ....

all:
    do something here

test:

    cd test
    make test

And then in my test/Makefile I want to be able to access the previous PACKAGES variable and add this makefile's individual dependencies onto it.

In the test/Makefile

PACKAGES += googletest googlemock

test
     do something here

Could anyone help me solve this problem?

Upvotes: 19

Views: 17891

Answers (3)

Jossy Sebastian
Jossy Sebastian

Reputation: 155

export PACKAGES = jansson mysql ....

Upvotes: -2

Some programmer dude
Some programmer dude

Reputation: 409166

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

Upvotes: 10

UmNyobe
UmNyobe

Reputation: 22890

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

Upvotes: 21

Related Questions