61

I think this is a question that has been asked many times but I cannot find the right way to do it.

I have the following structure:

project/
project/Makefile
project/code
project/code/*.cc
project/code/Makefile

When I am in the directory 'project/code' and call "make project_code" my code is compiling correctly.

I would like to do that when I am in 'project/', just calling "make project_code" as if I was in 'project/code'.

The makefile 'project/Makefile' will contain other rules (such as 'install') and some rules to compile as if I was in 'project/code'. And for that, I am requesting your help... Thanks.

2 Answers 2

86

The simplest way is to do:

CODE_DIR = code

.PHONY: project_code

project_code:
       $(MAKE) -C $(CODE_DIR)

The .PHONY rule means that project_code is not a file that needs to be built, and the -C flag indicates a change in directory (equivalent to running cd code before calling make). You can use the same approach for calling other targets in the code Makefile.

For example:

clean:
       $(MAKE) -C $(CODE_DIR) clean
6
  • Thanks, it works ! One last thing: is $(MAKE) always defined ?
    – Cedric H.
    Aug 16, 2010 at 21:33
  • 2
    is $(MAKE) a reference to a variable you defined? Or is that a built in function that is always there?
    – mtmurdock
    Feb 8, 2011 at 23:07
  • It's built in to GNU Make, see the manual: gnu.org/software/make/manual/make.html#MAKE-Variable Feb 8, 2011 at 23:33
  • 1
    Is there a way to suppress the output of this call? @$(MAKE) doesn't work as expected.
    – musicmatze
    Jan 21, 2014 at 17:36
  • How can this be done for multiple subdirectories? When I try appending another subdirectory target to PHONY, only the first target is ran.
    – Michael
    Jun 15, 2014 at 14:07
1

Try putting this rule in project/Makefile something like this (for GNU make):

.PHONY: project_code
project_code:
       cd code && make
4
  • 17
    This will not work as written, because by default in GNU make, each line of a rule body is executed in a different shell. So, the cd will occur, but the shell that executed it will immediately exit; then 'make' will be executed separately. In fact, I believe this will put make into an infinite recursion loop. However, if you change you code to 'cd code && make', it will work as expected. Aug 17, 2010 at 0:57
  • 9
    Edited after 4 years to match the suggestion Aug 1, 2014 at 19:01
  • 5
    @EmanueleCipolla Thumb up after another four years to salute the spirit.
    – h9uest
    Oct 18, 2014 at 15:18
  • 1
    And here we are almost four years to the date, again which only proves that make is a timeless piece of software and proper Makefile writing should be a part of every basic computer skills course.
    – hlecuanda
    Jul 3, 2018 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.