Getting the makefile is in

What is the correct way to get the directory where the current makefile executable is located?

I am currently using export ROOT=$(realpath $(dir $(lastword $(MAKEFILE_LIST)))) , and I encounter some problems when you run make with exactly the same parameters and you get different values ​​for ROOT. In approximately 90% of cases, it has the correct value, but in the remaining 10%, there are several invalid paths.

+4
source share
3 answers

realpath , abspath , lastword and a few other functions were introduced only in GNU Make 3.81 [See ref]. Now you can get the current file name in older versions using words and word :

 THIS_MAKEFILE:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) 

But I'm not sure of a realpath for realpath without going into the shell. for example, this works with make v3.80:

 THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) THIS_MAKEFILE:=$(notdir $(THIS_MAKEFILE_PATH)) all: @echo "This makefile is $(THIS_MAKEFILE) in the $(THIS_DIR) directory" 

What gives

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

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

+10
source

$ (shell pwd) is invalid because a makefile may exist in a directory other than pwd (as permitted by make -f ).

Suggested by OP

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

excellent, except that he probably wants to use firstword instead, especially if the makefile (potentially) include top level (makefile) of another makefile before it is bound to ROOT.

The problem with 10% OPs can be explained if there is a conditional inclusion 10% of the time before the appointment, but, hey, this is an assumption ...

+4
source

For your convenience, when GNU starts (after it has processed any -C options), it sets the CURDIR variable to the path to the current working directory. Never touch this value, do it again: in particular, note that if you include files from other directories, the CURDIR value does not change. The value has the same priority as if it were set in the makefile (by default, the CURDIR environment variable will not override this value). Please note that setting this variable does not affect make (it does not make make change its working directory, for example).

all: echo $ (CURDIR)

+1
source

Source: https://habr.com/ru/post/1333686/


All Articles