gnu-makemakefilemultiple-makefiles

How to compile multiple simple projects with GNU make


I am trying to implement various project from a programming book. My intention was to have each project exercise in its own folder and then have a makefile that compiles all of them with something like a make all. The folder structure is like this:

.
├── Makefile
├── bin
│   ├── prog1
│   ├── prog2
│   └── prog3
└── src
    ├── prog1
    │   ├── Makefile
    │   └── main.c
    ├── prog2
    │   ├── Makefile
    │   └── main.c
    └── prog3
        ├── Makefile
        └── main.c

I would like to learn how to set up such a structure. In particular the part where the top makefile visit all folders in src calls make there, and then copies and renames the executable into the bin folders.


Solution

  • There are different ways to tackle this, but something like this should work for your example:

    PROGS := bin/prog1 bin/prog2 bin/prog3
    
    all: $(PROGS)
    
    $(PROGS):
        $(MAKE) -C src/$(@F)
        mkdir -p $(@D)
        cp src/$(@F)/main $@
    
    .PHONY: clean
    
    clean:
        rm -f $(PROGS)
        for t in $(PROGS); do make -C src/`basename $$t` clean; done
    

    We define a list of targets (PROGS) we are to build. We say these targets are prerequisites of all and then we go ahead and define how they should be built, that is: we recursively descent into src/ plus filename part of the target to run make there. We create directory of the target to be sure it's there and copy main from the directory we've descended to the path of the target.

    For a good measure, there is a clean target as well that removes all the PROGS and runs make clean recursively in src/.