Makefile

Für kleinere Projekte oder ad hoc Aufgaben in C++ ist es nützlich ein universelles Makefile bei der Hand zu haben. Daher hab ich etwas im Internet recherchiert und aus den folgenden beiden Quellen ein Makefile für meine Zwecke gebaut.

### Start of user configuration ###########################################

# Name your executable.
TARGET = application

# Additional paths for PKG_CONFIG_PATH.
PKG_CONFIG_PATH =

# Additional libs, flags will be created with pkg-config.
LIBS =

# User flags.
CXXFLAGS =
LDFLAGS =

### End of user configuration #############################################

# Default build type.
TYPE = debug

# Special flags for each build type.
ifeq ($(TYPE),debug)
CXXFLAGS := $(value CXXFLAGS) -O0 -g3
LDFLAGS := $(value LDFLAGS)
endif

ifeq ($(TYPE),profile)
CXXFLAGS := $(value CXXFLAGS) -pg
LDFLAGS := $(value LDFLAGS) -pg
endif

ifeq ($(TYPE),release)
CXXFLAGS := $(value CXXFLAGS) -O3
LDFLAGS := $(value LDFLAGS) -s
endif

# The source, include and object store directory.
SRCDIR = src
INCDIR = include
OBJDIR = .$(TYPE)

# Compiler and compiler options.
CXX = g++
CXXFLAGS := $(value CXXFLAGS) -Wall -I$(INCDIR) -I$(SRCDIR) $(if $(LIBS),\
	$(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) pkg-config --cflags $(LIBS)))

# Linker and linker options.
LD = g++
LDFLAGS := $(value LDFLAGS) $(if $(LIBS),\
	$(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) pkg-config --libs $(LIBS)))

# List of source files.
SRCS := $(foreach FILE,$(shell find $(SRCDIR) -name *.cpp | xargs), \
	$(subst $(SRCDIR)/, , $(FILE)))
# List of object files.
OBJS := $(addprefix $(OBJDIR)/,$(SRCS:.cpp=.o))
# List of dependency files.
DEPS := $(addprefix $(OBJDIR)/,$(SRCS:.cpp=.d))

.PHONY: init clean

$(TARGET): init $(OBJS)
	$(LD) $(LDFLAGS) -fPIC $(OBJS) -o $(TARGET)

$(OBJDIR)/%.o: $(SRCDIR)/%.cpp
	$(CXX) -Wp,-MMD,$(OBJDIR)/$*.dd $(CXXFLAGS) -fPIC -c $< -o $@
	@sed -e '1s/^\(.*\)$$/$(subst /,\/,$(dir $@))\1/' $(OBJDIR)/$*.dd > \
		$(OBJDIR)/$*.d
	@rm -f $(OBJDIR)/$*.dd

init:
	@if [ ! -e $(OBJDIR) ]; then mkdir $(OBJDIR); fi;
	@$(foreach DIR,$(sort $(dir $(SRCS))), if [ ! -e $(OBJDIR)/$(DIR) ]; \
		then mkdir $(OBJDIR)/$(DIR); fi; )

clean:
	@rm -f $(TARGET) $(OBJS)

-include $(DEPS)
Tagged als: , ,

Kommentieren