In Unix, can I run make
in a directory without cd
'ing to that directory first?
Asked
Active
Viewed 8.5k times
243

Guy Avraham
- 3,482
- 3
- 38
- 50

user46795
- 2,643
- 3
- 25
- 31
5 Answers
389
-
10Grump - that isn't in standard make; it must be a GNU extension. Since you say Linux and Unix, it isn't clear which you want, but the -C option won't work on Solaris 10 (/usr/ccs/bin/make), AIX (/usr/bin/make), or HP-UX 11.23 (/usr/bin/make). Still, 1 out of 4 isn't too bad. – Jonathan Leffler Jan 24 '09 at 04:17
-
7It works in BSD make as well, so its not just a GNU extension. – Chris Dodd Jun 28 '13 at 17:00
-
4make sure 'C' is in upper case. – Rezaeimh7 Sep 25 '16 at 06:56
-
2Or use `--directory=` which does the same. – Melroy van den Berg Oct 16 '20 at 23:54
106
As noted in other answers, make(1) has a -C
option for this; several commands have similar options (e.g. tar). It is useful to note that for other commands which lack such options the following can be used:
(cd /dir/path && command-to-run)
This runs the command in a sub-shell which first has its working directory changed (while leaving the working directory of the parent shell alone). Here &&
is used instead of ;
to catch error cases where the directory can not be changed.

Dave C
- 7,729
- 4
- 49
- 65
23
If the reason you don't want to cd to a directory is because you need to stay in the current directory for a later task, you can use pushd and popd:
pushd ProjectDir ; make ; popd
That goes into the ProjectDir, runs make, and goes back to where you were.

Robert Siemer
- 32,405
- 11
- 84
- 94

EnigmaCurry
- 5,597
- 2
- 23
- 15
-4
makefile:
all:
gcc -Wall -Wpedantic -std=gnu99 -g src/test.c -o build/test
run:
./build/test
or
run:
./../build/test
etc.

oldpilsbury
- 1
- 5
-
3The answer completely missed the question - it is about how to invoke make, not how to write makefile. – Petr Jan 15 '19 at 09:42