Phocs
Phocs

Reputation: 2510

Smart Makefile: way scan directory tree and compile .c files

I am doing a project which is growing pretty fast, but my Makefile has a strong dependence on filenames.

my directory tree: Makefile source source/phase2 source/include

this directory are create from Makefile: exec_phase2.test source/build

this is part of my Makefile

# Project path
PH2 = source
SRC_PH2 = $(PH2)/phase2
INCL_PH2 = $(PH2)/include
EXEC_PH2 = exec_phase2.test
BUILD_PH2 = $(PH2)/build

# Header file path
HEAD_PH2 = $(INCL_PH2)/const.h $(INCL_PH2)/listx.h $(INCL_PH2)/mikabooq.h

# Object files path
OBJECTS_PH2 = $(BUILD_PH2)/main.o $(BUILD_PH2)/mikabooq.o $(BUILD_PH2)/testP.o


all: mikaboo

mikaboo: phase2.test

phase2.test: clean buildOutDir coreFile

buildOutDir: 
    mkdir -p $(BUILD_PH2)
    mkdir -p $(EXEC_PH2)

coreFile: $(EXEC_PH2)/main.elf
    $(ELF) $(ELFFLAG) $<

$(EXEC_PH2)/main.elf: $(OBJECTS_PH2)
    $(LD) $(LDFLAG) $(LINKER_UARM_PH2)

$(BUILD_PH2)/main.o: $(SRC_PH2)/main.c $(BUILD_PH2)/mikabooq.o $(HEAD_PH2)
    $(CC) $(CCFLAGS) $@ $<

$(BUILD_PH2)/mikabooq.o: $(SRC_PH2)/mikabooq.c $(HEAD_PH2)
    $(CC) $(CCFLAGS) $@ $<

$(BUILD_PH2)/testP.o: $(SRC_PH2)/testP.c $(HEAD_PH2) $(HEAD_KER)
    $(CC) $(CCFLAGS) $@ $<

clean:
    rm -rf $(BUILD_PH2) $(EXEC_PH2) 

I would like automatize the search of sources and header file: I see these two command:

#search all source file name
SOURCES := $(shell find $(SOURCEDIR) -name '*.c')
# Make list of object files with paths
OBJECTS := $(addprefix $(BUILDDIR)/,$(SOURCES:%.c=%.o))

Ok I think that this can work, but now how I can automatically compile all .c file with their dependencies?

Note: I am not that used to makefiles, I know the basics.

Upvotes: 2

Views: 271

Answers (1)

Frank-Rene Sch&#228;fer
Frank-Rene Sch&#228;fer

Reputation: 3352

Generate a bunch of rules using foreach. CCompilation below implements the template recipe to be used by foreach on every directory being mentioned in $(SOURCES). Note, that the last free line in the recipe is an important delimiter.

$(foreach DIRECTORY, $(dir $(SOURCES)), 
          $(call CCompilation, OUTPUT_DIRECTORY, EXTRA_STUFF, $(DIRECTORY)))

define CCompilation 
$(1)/%.o: $(3)/%.c
    CC $< $(2) -o $$@

endef 

Upvotes: 0

Related Questions