73

In order to run make file, I am supposed to go to the make file's directory and from there only I can run the make file. How can I do the same even if i am in any directory?

Dinesh
  • 909
  • 1
  • 7
  • 12
  • 1
    Which `make`? Borland's `make`? GNU `make`? Microsoft's `nmake`? One of the umpteen shareware implementations of `make` that have floated around over the years? And on what platform? The answer is different depending from the specifics. `RedGrittyBrick` is presuming that you have a POSIX-conformant shell and filesystem, for example. – JdeBP Dec 23 '11 at 13:43
  • do `make -C dir` – Charlie Parker Sep 09 '22 at 18:05

4 Answers4

85

General solution

(cd /other/dir && make)

will not change your shell's current directory (because the brackets contents are run in a subshell), but will run make with the indicated working directory.

The && will ensure that make doesn't run if there's an error in the cd part of the command (e.g., the directory doesn't exist, or you don't have access to it).

The above approach is useful for all sorts of commands, not just make. For this reason it is worth learning and remembering.

Specific solution

Check the man page for a -C option, e.g.

make -C /other/dir

Several Unix commands started out without this option but had it added to them at some time (e.g. with GNU implementation)

RedGrittyBrick
  • 81,981
  • 20
  • 135
  • 205
  • 11
    Looks like there's a `-C` option to make for most Unixes these days. Details and some more complete answers here: http://stackoverflow.com/q/453447/357774 – Noyo Oct 24 '13 at 13:34
  • why will that not change the directory? – Charlie Parker Sep 09 '22 at 18:02
  • 1
    @CharlieParker the brackets `()` causes the command to be run in a subshell, changes to current-working-directory made in the subshell do not affect the parent shell. When the command finishes, the subshell exits and control returns to the parent shell. I've updated this (11-year old) answer to make that explicit. – RedGrittyBrick Sep 09 '22 at 18:45
56

You could use

make -C dir

to change to directory dir before reading the pointed makefile. Please notice that option -C is capitalized.

zyy
  • 179
  • 9
Jonathan
  • 661
  • 5
  • 3
2

This is an old question but I like to use a ~/.bashrc alias, which looks like this:

alias makeaway="cd /dir/to/make && make && cd -"
JW0914
  • 7,052
  • 7
  • 27
  • 48
1

Use cd ./dir && make && pwd inside Makefile .

Example of sample Makefile :

BUILD_DIR       =       $(shell pwd)

deploy::
        cd ./dist/local && make && pwd && npm publish && cd .. && cd .. && pwd
clean::
        npm cache clean --force
I say Reinstate Monica
  • 25,487
  • 19
  • 95
  • 131
  • The && was exactly what I needed to change a directory and execute a command there, then drop back to the main folder to finish the build. – Brady Dec 06 '20 at 18:15