Recursive makefile

I extended a Makefile, developed by Dr. R. K. Owen for general purposes. It’s usage is very simple. Put this Makefile in one directory above your source code. It considers that all your code are in a directory named ‘src’. It will search recursively on sub-directories of ‘src’ directory, generate the object code .o and link them all. There is also some debug flags and optimization flags that can be used or removed according to the situation.

# ----------------------------------------------------------------------------
# Makefile
# 
# release: 0.1 (28-Ago-2010) create makefile
# 
# purpose: searches recursively in current directory for c/cpp files (using find),
#          compile each source file and link them in a executable.
# ----------------------------------------------------------------------------

APP     = simulator
CC      = gcc
RM      = rm
SRCDIR  = src
SRCEXT  = c
OBJDIR  = obj

SRCS    := $(shell find $(SRCDIR) -name '*.$(SRCEXT)')
SRCDIRS := $(shell find . -name '*.$(SRCEXT)' -exec dirname {} \; | uniq)
OBJS    := $(patsubst %.$(SRCEXT),$(OBJDIR)/%.o,$(SRCS))

DEBUG   = -pg
INCLUDE = -I./inc
CFLAGS  = -Wall -DEBUG -lm -c $(DEBUG) $(INCLUDE)
OFLAGS  = -lm -msse2 -ffast-math -ftree-vectorize

all:    $(APP)

$(APP): buildrepo $(OBJS)
        @echo "$(CC) $(OFLAGS) $(OBJS) -o $@"
        @$(CC) $(OBJS) $(OFLAGS) -o $@

$(OBJDIR)/%.o: %.$(SRCEXT)
        @echo "$(CC) $(CFLAGS) $< -o $@"
        @$(CC) $(CFLAGS) $< -o $@

clean:
        $(RM) -r $(OBJDIR)

buildrepo:
        $(call make-repo)

define make-repo
        for dir in $(SRCDIRS); \
        do \
                mkdir -p $(OBJDIR)/$$dir; \
        done
endef

See ya!

Advertisements