1

Say my directory structure is this:

foo
foo/Makefile
foo/bar

Now say foo/Makefile has a make target baz.

I want to call make baz from foo/bar without creating another Makefile in the bar subdirectory. Is this possible?

Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51

1 Answers1

0

GNU make has two important options for your situation: -f FILE is used to tell make which makefile(s) to use instead of the defaults and -C DIR tells make to change to directory DIR before reading the makefiles. How to use one or the other or both depends on your specific case. Note that -f is compliant with the POSIX standard while -C is an extension supported by GNU make. If -C is not supported by your own version of make and has no equivalent you will have to change the current directory yourself before invoking make, e.g. ( cd some/where; make...; ).

  1. If you can build baz from foo/bar/, as suggested by Oo.oO, you can simply

     make -f ../Makefile baz
    

    make will run from foo/bar/ and build baz as indicated in ../Makefile.

  2. If you must be in foo/ to build baz you should use:

     make -C .. baz
    

    make will change to .., that is, foo before reading the makefiles and as it will find here one of the defaults (Makefile) it will use it to discover how to build baz.

  3. If you must be in another directory, e.g. the parent of foo/, you need both options and type:

     make -C ../.. -f foo/Makefile baz
    

    make will first change to ../.. (parent directory of foo/) and from here it will use foo/Makefile to discover how to build baz.

Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51
  • Thanks for this detailed answer. Is there a way to do this without adding new flags? Say I am working on a complex directory structure, it is not feasible to create a new Makefile for each directory. I’m considering the best way to do this is via a bash script. – Chukwudi Derek Uche Aug 05 '20 at 15:59
  • You should probably try to explain a bit better what you would like to do and, more important, what are your constraints. I do not really understand why using `make` options is a problem. – Renaud Pacalet Aug 05 '20 at 16:32
  • My question is, if there is no Makefile in a directory, how can you make it default to the Makefile in the parent directory without adding options. Is this something that is possible? – Chukwudi Derek Uche Aug 05 '20 at 18:25
  • @ChukwudiDerekUche: Well, you could download the make sources, modify them such that it also searches the default makefiles in the parent directory, and recompile. You could also create symbolic links. You could also define a shell function or alias to wrap make inside a simple script that does all this for you. Example if your makefiles are always named `Makefile`: `function my_make { if [ ! -f Makefile ] && [ -f ../Makefile ]; then make -f ../Makefile $*; else make $*; fi }`. But there are some side effects that you should probably consider (`$(MAKE)`, etc.) – Renaud Pacalet Aug 07 '20 at 11:55