makefilegnu-makebsdmake

GNU Make: chdir make process itself


Is it possible to use a makefile that directs the make process itself to chdir? I want to write a makefile that expects to be executed from the build directory.

Suppose I have a project directory structure that looks like this

project/
├── Makefile
├── include
│   └── Foo.h
├── src
│   └── Foo.cpp
└── test
    └── FooTest.cpp

and the first thing the make directory does is make a build directory.

project/
├── Makefile
├── _build
├── include
│   └── Foo.h
├── src
│   └── Foo.cpp
└── test
    └── FooTest.cpp

Is it possible to direct the makefile to chdir into _build to simplify my rules?

I want to be able to write (for example)

foo : Foo.o
    $(LD) $^ -o $@ $(LDFLAGS)

rather than

_build/foo : _build/Foo.o
    $(LD) $^ -o $@ $(LDFLAGS)

I know I can add the build directory to the VPATH in order to affect path resolution, but it seems cleaner to just chdir Make itself. Is there a way to do this (preferably without using guile)?


Solution

  • You can make a simple Makefile that forwards everything:

    .DEFAULT_GOAL := all
    .PHONY: ${MAKECMDGOALS}
    $(filter-out all,${MAKECMDGOALS}) all: .forward-all ; @:
    .forward-all:
            ${MAKE} -C build ${MAKECMDGOALS}
    # Never try to remake this makefile.
    ${MAKEFILE_LIST}: ;
    .SUFFIXES: