Getting the name of the makefile from the makefile

Viewed 18565

How to get the name of the makefile in the makefile?

Thanks.

Note:

I would need that because I would like my makefile to call itself, but the makefile is not called Makefile, so I'd like to write something like this:

target:
    ($MAKE) -f ($MAKEFILENAME) other_target
7 Answers

This returns the name of the first Makefile called, i.e. the one at the bottom of the call stack:

MAKEFILE_JUSTNAME := $(firstword $(MAKEFILE_LIST))
MAKEFILE_COMPLETE := $(CURDIR)/$(MAKEFILE_JUSTNAME)

When used in non-cross-recursive situations (e.g. for makedepend), it is just the name of the current makefile.

The solutions here addresses 1) POSIX make with 2) Invoked, non included, makefile in 3) A Unix alike platform.

What the OP asked for:

target:
    @pid=$$$$; \
    while test `ps -ocomm= $$pid` != make; do \
        pid=`ps -oppid= $$pid`; \
    done; \
    MAKEFILENAME=`ps -oargs= $$pid|sed 's/^.* -f *\([^ ]*\).*$$/\1/'`; \
    test -z "$$MAKEFILENAME" -a -f Makefile && MAKEFILENAME=Makefile; \
    test -z "$$MAKEFILENAME" -a -f makefile && MAKEFILENAME=makefile; \
    export MAKEFILENAME; \
    $(MAKE) -e -f $$MAKEFILENAME other_target

The targets depends on the makefile, kind of bloated:

TARGET1_MAKEFILENAME = target1_preamble

all: target1 target2...

target1: $(TARGET1_MAKEFILENAME) other_dependencies...
    @test $(TARGET1_MAKEFILENAME) == target1_preamble && exit 0; \
    built_instructions_for_target1;

target1_preamble:
    @pid=$$$$; \
    while test `ps -ocomm= $$pid` != make; do \
        pid=`ps -oppid= $$pid`; \
    done; \
    MAKEFILENAME=`ps -oargs= $$pid|sed 's/^.* -f *\([^ ]*\).*$$/\1/'`; \
    test -z "$$MAKEFILENAME" -a -f Makefile && MAKEFILENAME=Makefile; \
    test -z "$$MAKEFILENAME" -a -f makefile && MAKEFILENAME=makefile; \
    export MAKEFILENAME; \
    $(MAKE) -e -f $$MAKEFILENAME target1;

Can be a bit simplified if make is invoked only for all targets.

MAKEFILENAME = invoked_makefile_placeholder

all: target1 target2...

target1: $(MAKEFILENAME) other_dependencies...
    @test $(MAKEFILENAME) == invoked_makefile_placeholder && exit 0; \
    built_instructions_for_target1;

invoked_makefile_placeholder:
    @pid=$$$$; \
    while test `ps -ocomm= $$pid` != make; do \
        pid=`ps -oppid= $$pid`; \
    done; \
    MAKEFILENAME=`ps -oargs= $$pid|sed 's/^.* -f *\([^ ]*\).*$$/\1/'`; \
    test -z "$$MAKEFILENAME" -a -f Makefile && MAKEFILENAME=Makefile; \
    test -z "$$MAKEFILENAME" -a -f makefile && MAKEFILENAME=makefile; \
    export MAKEFILENAME; \
    $(MAKE) -e -f $$MAKEFILENAME

With the previous approach is trivial to implement a solution for included makefiles based in grep and a unique pattern contained in the makefile.

I never answer when I feel the question got a proper solution.

Related