Monday, September 08, 2008

C++: Simple Makefile Example

I have always been looking for a nice makefile template, that will allow me to have separate include, src, and obj directories. Today I stumbled on addprefix a directive that allows me to add only the filename of each src file I add to my project.

Assuming you have the files
./Makefile
./include/file1.h
./include/file2.h
./include/file3.h
./src/file1.cpp
./src/file2.cpp
./src/file3.cpp
and all obj files go in ./obj/
and your target executable is ./execfile


Makefile
CC        =g++
CFLAGS =-c -Wall
LDFLAGS =
INCLUDE =-I./include
OBJDIR =obj/
OBJLIST = file1.o file2.o file3.o
OBJECTS = $(addprefix $(OBJDIR), $(OBJLIST) )

all:execfile

execfile: $(OBJECTS)
[TAB]$(CC) $(LDFLAGS) $(OBJECTS) -o $@

$(OBJECTS): obj/%.o: src/%.cpp
[TAB]$(CC) $(CFLAGS) $? -o $@ $(INCLUDE)

clean:
[TAB]rm -rf obj/*.o
obviously, replace [TAB] with the actual tab character(\t).

No comments: