Share variables between makefiles

笑着哭i 提交于 2019-12-20 12:21:09

问题


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?

Thanks


回答1:


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




回答2:


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



回答3:


export PACKAGES = jansson mysql ....



来源:https://stackoverflow.com/questions/14880419/share-variables-between-makefiles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!