Skip to content

Instantly share code, notes, and snippets.

@mrajcok
Created October 3, 2010 01:26
Show Gist options
  • Save mrajcok/608167 to your computer and use it in GitHub Desktop.
Save mrajcok/608167 to your computer and use it in GitHub Desktop.
C++ Makefile
#
# !!!!!!!!!! REPLACE LEADING SPACES WITH TABS !!!!!!!!!!!!!!!!
#
# This GNU makefile http://www.gnu.org/software/make/manual/make.html
# supports 'debug' and 'release' builds of a C++ project.
# It also handles header file dependencies.
# The makefile requires all source files and the makefile to be in one directory.
# To build the debug build: (.o, .d, and executable are put into ./debug)
# $ make # or make -jn for building in parallel
# To build a release build: (.o, .d, and executable are put into ./release)
# $ make RELEASE=1
# You should only have to edit the following lines for your project:
PROG = my_prog
ifdef windir
PROG = my_prog.exe
endif
SOURCES = src1.cpp src2.cpp
DEFS = -D...
LDLIBS = -lboost_thread
CPPFLAGS += -Wall -I. $(DEFS)
ifdef windir
CPPFLAGS += -DBOOST_THREAD_USE_LIB
endif
ifdef RELEASE
CPPFLAGS += -O2
else
ifdef GDB
CPPFLAGS += -ggdb
else
CPPFLAGS += -g
endif
endif
INSTALL_DIR = bin
# Normally, leave the rest of this Makefile as is
CXX = g++ # ensure GNU
CC = g++ # ensure GNU -- many use gcc here, but I get linker errors using gcc
# set OUTPUT_DIR according to build type
ifdef RELEASE
OUTPUT_DIR = release
else
OUTPUT_DIR = debug
endif
# below, convert each src, e.g., src1.cpp, to debug/src1.o and debug/src1.d
OBJS = $(SOURCES:%.cpp=$(OUTPUT_DIR)/%.o)
DEPS = $(SOURCES:%.cpp=$(OUTPUT_DIR)/%.d)
# default target, with implicit build rules
$(OUTPUT_DIR)/$(PROG): $(OBJS)
# the next line seems to be needed sometimes (remove this line)
$(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@
$(OUTPUT_DIR)/%.o: %.cpp
$(CXX) $(CPPFLAGS) -c -o $@ $<
.PHONY: clean # .PHONY = always build target (don’t look for it in the filesystem)
clean:
ifdef windir # below, "\" needed for windows
del $(OUTPUT_DIR)\$(PROG) $(SOURCES:%.cpp=$(OUTPUT_DIR)\\%.o) $(SOURCES:%.cpp=$(OUTPUT_DIR)\\%.d)
else
rm -f $(OUTPUT_DIR)/$(PROG) $(OBJS) $(DEPS)
endif
.PHONY: install
install: # this target likely only works on UNIX/Linux
ifdef windir
mkdir $(INSTALL_DIR)
copy $(OUTPUT_DIR)/$(PROG) $(INSTALL_DIR)
else
mkdir -p $(INSTALL_DIR)
cp -p $(OUTPUT_DIR)/$(PROG) $(INSTALL_DIR)
endif
$(OUTPUT_DIR)/%.d: %.cpp # -MM finds hdr file dependencies, excludes system hdrs
$(CXX) -MM -MF $@ -MT $(@:.d=.o) -MT $@ $<
# e.g., $(CXX) -MM -MF debug/test.d -MT debug/test.o -MT debug/test.d
# "-" means be silent about missing files, such as removed .hpp files
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)
endif
@ArashPartow
Copy link

A comprehensive and easy to use C++ Makefile example can also be found here:

https://www.partow.net/programming/makefile/index.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment