Chan Kim
Chan Kim

Reputation: 5959

how to set the directory where Makefile exists so that I can run make from different directory using `make -C` option?

Say in ~/prj/abc/abcsim/abctsim/abcxyz/Makefile there is a line below.

TOOLCHAIN_DIR   := $(PWD)/../../../prj1/tools/gcc_tools  

If I'm in directory ~/test, and if I run make -C ~/prj/abc/abcsim/abctsim/abcxyz, this doesn't work because the $(PWD) variable is set to ~/test, not ~/prj/abc/abcsim/abctsim/abcxyz. How can I get the directory path where the Makefile exists?
In bash there's something for this : How can I get the source directory of a Bash script from within the script itself?

Upvotes: 0

Views: 293

Answers (1)

Renaud Pacalet
Renaud Pacalet

Reputation: 29202

If you really use make -C (not make -f) and your Makefile is not included in another, you can simply use the CURDIR variable. GNU make sets it to the absolute path of the current directory when it starts, "after it has processed any -C options". So, in your case it should do exactly what you want.

Else, if you sometimes use make -f or if you have included Makefiles, you can put this as the first line of any of your Makefiles (or, at least, before any include statement):

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

and then use $(HERE) to refer to this Makefile's directory. See the GNU make manual for the details.

Note: I was almost sure this question would be a duplicate. Surprisingly I searched SO for a clear answer and found only old answers that first suggest shell calls before using make built-ins or wrong answers (using firstword instead of lastword, for instance).

Upvotes: 2

Related Questions