Thursday, January 8, 2015

Recursive Makefile for Sub-Directories

                 As we know, compiling is very tedious work, specially when we want to include several source files and have to type the compiling command every time we want to do compiling. It is even more difficult when our source files are in nested sub- directories.  To escape from these tedious work most of the people create Makefile. Makefile is a special format file that together with the make utility will help to automatically compile our several source files. The advantage of using Makefile is that it performs incremental compilation.

              Here, I would like to share a Makefile which is capable of compiling source files presented in nested sub-directories, creating objects of each source file in its directory and creating a binary from all object files presented in nested sub-directories. (NOTE: if you are using following Makefile, make sure to use tab at required places)

Makefile
***********

PREFIX            = /usr/local
INCLUDE        = /usr/include/X11/
PWDDIR          = $(shell pwd)
CXX                  = g++
RM                   = rm -vf
CONSTANTS   = -D__GXX_EXPERIMENTAL_CXX0X__       
CPPFLAGS      = -O0 -g3 -Wall -c -fmessage-length=0 -fpermissive -std=c++0x
LDFLAGS        = -lX11 -lXi -lXtst -lm
BINARY           = gframework_demo
DEPS               = $(shell find . -name '*.hpp')
SRCFILES       = $(shell find . -name '*.cpp')
OBJFILES        = $(SRCFILES:%.cpp=%.o)

all: $(BINARY)

$(BINARY): $(OBJFILES)
    $(CXX) -I$(INCLUDE) -o "$(BINARY)" $(OBJFILES) $(LDFLAGS)

%.o: %.cpp $(DEPS)
     $(CXX) $(CONSTANTS) -I$(INCLUDE) -I"$(PWDDIR)" $(CPPFLAGS) -c $< -o $@

clean:
    $(RM) $(shell find . -name '*.o') *~
    $(RM) $(BINARY)

install: $(BINARY)
    install -m 0755 $(BINARY) $(PREFIX)/bin
       
.PHONY: install