Sample [Makefile]

Every time anyone asks me how to write a Makefile I need to write a sample Makefile from scratch for them. So, writing one here so that I can just give this link and explain.

# Sample Makefile
CC:= g++
LD:= g++

ROOT_DIR:= ${PWD}
SRC_DIR:= ${ROOT_DIR}/src
TARGET_DIR:= ${ROOT_DIR}/bin
INCLUDES_DIR:= ${ROOT_DIR}/include

SRC_FILES:= ${SRC_DIR}/test.cpp\
            ${SRC_DIR}/foo.cpp

INCLUDES:= -I. -I${INCLUDES_DIR}
OBJ_FILES:= $(patsubst %.cpp,%.o,$(SRC_FILES)

CFLAGS:= -c -Wall ${INCLUDES}
LDFLAGS:=

ifeq (${BUILD}, debug)
CFLAGS += -g
endif

TARGET:= ${TARGET_DIR}/testapp
all: ${TARGET}

${TARGET}: ${OBJ_FILES}
${LD} ${LDFLAGS} $^ -o $@

%.o: %.cpp
${CC} ${CFLAGS} $^ -o $@

clean:
rm -f ${TARGET} ${OBJ_FILES}

.PHONY: clean

No comments: