How to call Makefile from another Makefile?

Chris Tonkinson picture Chris Tonkinson · Feb 5, 2010 · Viewed 149k times · Source

I'm getting some unexpected results calling one makefile from another. I have two makefiles, one called /path/to/project/makefile and one called /path/to/project/gtest-1.4.0/make/Makefile. I'm attempting to have the former call the latter. In /path/to/project/makefile, I have

dev: $(OBJ_FILES)
  $(CPPC) $(LIBS) $(FLAGS_DEV) $(OBJ_FILES) -o $(BIN_DIR)/$(PROJECT)
  $(MAKE) -f ./gtest-1.4.0/make/Makefile

clean:
  rm -f ./*~ ./gmon.out ./core $(SRC_DIR)/*~ $(OBJ_DIR)/*.o
  rm -f ../svn-commit.tmp~
  rm -f $(BIN_DIR)/$(PROJECT)
  make -f gtest-1.4.0/make/Makefile clean

And in /path/to/project/gtest-1.4.0/make/Makefile I have

all: $(TESTS)

clean:
  rm -f $(TESTS) gtest.a gtest_main.a *.o

Issuing the following:

cd /path/to/project
make

Outputs:

make -f ./gtest-1.4.0/make/Makefile
make[1]: Entering directory `/path/to/project'
make[1]: Nothing to be done for `all'.
make[1]: Leaving directory `/path/to/project'

However, when I issue these commands:

cd /path/to/project
make clean

I see:

make -f gtest-1.4.0/make/Makefile clean
make[1]: Entering directory `/path/to/project'
rm -f  gtest.a gtest_main.a *.o
make[1]: Leaving directory `/path/to/project'

I don't understand: In both cases, /path/to/project/makefile is telling me it's entering the current working directory. In the first case, it doesn't think it has work to do (when it does) and in the second case, it's able to find the appropriate directive (when the output is telling me it's looking in the wrong directory) yet it tries to run the rm command in /path/to/project, instead of /path/to/makefile/gtest-1.4.0/make/.

Am I missing something fundamental to calling makefiles from one another? Have I made an egregious conceptual mistake, or hit a common pitfall? How do I effectively change directories and call a second makefile from within the first? My understanding was that simply calling make -f <name> would be enough.

This is make/gmake 3.81 in bash.

Answer

Tader picture Tader · May 2, 2012

Instead of the -f of make you might want to use the -C <path> option. This first changes the to the path '<path>', and then calles make there.

Example:

clean:
  rm -f ./*~ ./gmon.out ./core $(SRC_DIR)/*~ $(OBJ_DIR)/*.o
  rm -f ../svn-commit.tmp~
  rm -f $(BIN_DIR)/$(PROJECT)
  $(MAKE) -C gtest-1.4.0/make clean