Aart Stuurman
Aart Stuurman

Reputation: 3628

Makefile - get directory of itself from within included file

Say a makefile includes multiple other makefiles. How can these included makefiles get to know the path to themselves relative to the main makefile?

An example structure is as follows:

main make:

include ../dir1/dir2/make1.mk
include dir3/dir4/dir5/make2.mk

.PHONY: print_paths
print_paths:
    @echo $(dir1) && @echo $(dir2)

make1

dir1 = <some code>

make2

dir2 = <some code>

My expected output would be:

../dir1/dir2
dir3/dir4/dir5

I was able to solve this for a single include file through:

dir1 = $(dir $(lastword $(MAKEFILE_LIST)))

However, this does not seem to work for multiple files, as both dir1 and dir2 will be set equal to the directory of makefile two. (which is fair I guess? It is the last file included after all)

Alternatively them getting to know their absolute path would be fine as well.

Upvotes: 2

Views: 1253

Answers (1)

Renaud Pacalet
Renaud Pacalet

Reputation: 29290

You could simply add:

dir1 := $(dir $(lastword $(MAKEFILE_LIST)))

at the beginning of ../dir1/dir2/make1.mk and:

dir2 := $(dir $(lastword $(MAKEFILE_LIST)))

at the beginning of dir3/dir4/dir5/make2.mk.

Upvotes: 4

Related Questions