Home > Software design >  One Makefile run for multiple directories
One Makefile run for multiple directories

Time:10-03

I want to execute my Makefile, in one go, on the 2 directories "phosphorus" and "bonus". In theory, executables and .o are generated well by putting a directory name in the Makefile (DIR=...). But, I don't know how I can do this process twice.

Project structure :

├── Makefile
├── phosphorus
│   ├── phosphorus.c
│   └── phosphorus-engine.c
└── bonus
    ├── bonus.c
    └── bonus-engine.c

2 directories, 5 files

Expected output :

make

├── Makefile
├── phosphorus
│   ├── app-phosphorus
│   ├── phosphorus.o
│   ├── phosphorus-engine.o
│   ├── phosphorus.c
│   └── phosphorus-engine.c
└── bonus
    ├── app-bonus
    ├── bonus.o
    ├── bonus-engine.o
    ├── bonus.c
    └── bonus-engine.c

Executables are the results of the 2 files.c : app-phosphorus and app-bonus.

Makefile

# compiler
CFLAGS=--std=c99 -Wall

# directories
DIRS=phosphorus bonus

# current directory
# what do I put here ?
DIR=

# executable
EXEC=$(DIR)/app-$(DIR)

# objects files
OBJECTS=$(DIR)/$(DIR).o $(DIR)/$(DIR)-engine.o

$(EXEC): $(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o $(EXEC)

%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

clean:
    $(RM) $(OBJECTS) $(EXEC) *~

distclean: clean
    $(RM) Makefile

Thanks for helping me.

CodePudding user response:

You can use a recursive approach:

ifdef DIR

# compiler
CFLAGS=--std=c99 -Wall

# executable
EXEC=$(DIR)/app-$(DIR)

# objects files
OBJECTS=$(DIR)/$(DIR).o $(DIR)/$(DIR)-engine.o

all: $(EXEC)

$(EXEC): $(OBJECTS)
        $(CC) $(CFLAGS) $(OBJECTS) -o $(EXEC)

%.o: %.c
        $(CC) -c $(CFLAGS) $< -o $@

clean:
        $(RM) $(OBJECTS) $(EXEC) *~

else

# directories
DIRS=phosphorus bonus

all clean:
        @for dir in $(DIRS); do \
                echo make $@ DIR=$$dir ; \
                $(MAKE) $@ DIR=$$dir ; \
        done
endif
  • Related