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
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 $@

        $(RM) -r $(OBJDIR)

        $(call make-repo)

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

See ya!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: