Search code examples
makefiledependenciesgnu-make

Calling makefile in a subdirectory


I have a source code folder structure as follows

src
 |-tests
 |-abc

I have a makefile in src which has a target called tests. tests has its own makefile which it uses to compile the source code into binary.(multiple targets).All that is managed by the Makefile in the test directory.

My src make file has the following targets.

all: main tests

main: $(DEPENDENCY IN SRC and ABC)
   command

tests: ??
     make -C tests

What dependancy can I specify for tests target in the main Makefile.. I don't want this Makefile to be aware of the source files in the tests folder.


Solution

  • Just declare the target as PHONY meaning that make will not check for any produced file. Instead it just always executes the rule, letting the secondary call to make to decide what needs to be built.

    Think about this: What happens if you have an aditional file src/tests? make will notice that the file already exists and, as no prerequisite is indicated, it will decide not to make that file. Preventing your rule tests from being executed.

    all: main tests
    
    main: $(DEPENDENCY IN SRC and ABC)
        # Recipes (That is the word to describe commands in a make rule)
    
    .PHONY: tests
    
    tests:
         $(MAKE) -C tests
    

    Also add the answer by Alex: using $(MAKE) is a good practice. And allows your makefiles to work independently from the name of the make program. Imagine that you have a distribution where the program is called xyz-make.