Obtaining directory makefile resides in

What is the correct way to get the directory where the currently executing makefile resides?

I'm currently using export ROOT=$(realpath $(dir $(lastword $(MAKEFILE_LIST)))) and am running into some problems where when running make with the exact same options will result in different values for ROOT. About 90%of the time it has the correct value, but in the remaining 10% there are a number of invalid paths.


realpath,abspath,lastword and a couple of more functions were only introduced in GNU Make 3.81 [See ref]. Now you can get the current filename in older versions using words and word:


But I am not sure of a workaround for realpath without going to the shell. e.g. this works with make v3.80:

THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)

        @echo "This makefile is $(THIS_MAKEFILE) in the $(THIS_DIR) directory"

Which gives

$ make -f ../M
This makefile is M in the /home/sandipb directory

Ref: http://cvs.savannah.gnu.org/viewvc/make/NEWS?revision=2.93&root=make&view=markup

$(shell pwd) is not correct since the makefile might exist in a directory other than pwd (as allowed by make -f).

The OP's proposed

export ROOT=$(realpath $(dir $(lastword $(MAKEFILE_LIST))))

is fine, except, s/he probably wants to use firstword instead, especially if the top level makefile (potentially) includes other makefile(s) prior to assiging to ROOT.

The OPs 10% problem could be explained if there was a conditional include 10% of the time prior to the assignment, but, hey, that's a guess...

For your convenience, when GNU make starts (after it has processed any -C options) it sets the variable CURDIR to the pathname of the current working directory. This value is never touched by make again: in particular note that if you include files from other directories the value of CURDIR does not change. The value has the same precedence it would have if it were set in the makefile (by default, an environment variable CURDIR will not override this value). Note that setting this variable has no impact on the operation of make (it does not cause make to change its working directory, for example).

all: echo $(CURDIR)

Need Your Help

Capybara, finding within a css element

ruby-on-rails testing cucumber capybara

I'm working with Ruby on Rails 3, Cucumber, and Capybara

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.