Create a gist now

Instantly share code, notes, and snippets.

@fclairamb /Makefile
Last active Dec 15, 2015

This is a simple skeleton to build C/C++ projects without complex setup.This can be useful if you receive a project with a lot of code source and don't want to provide an IDE generated Makefile or use automake.It obviously doesn't support headers dependencies. Changing elements within a struct or a class require a clean & build.
ifeq "$(PREFIX)" ""
PREFIX=/usr
endif
ifeq "$(DESTDIR)" ""
DESTDIR=/
endif
CC=$(CROSS_COMPILE)gcc
CXX=$(CROSS_COMPILE)g++
AR=$(CROSS_COMPILE)ar
ifeq "$(CONF)" ""
CONF=Debug
endif
ifeq "$(CONF)" "Release"
CFLAGS=-O2 -fPIC
DEFINES=-DNDEBUG
endif
ifeq "$(CONF)" "Debug"
CFLAGS=-O0 -g -fPIC
DEFINES=-DDEBUG
endif
CXXFLAGS=$(CFLAGS)
BUILD=build/$(CROSS_COMPILE)$(CONF)
DIST=dist/$(CROSS_COMPILE)$(CONF)
NAME=mybin
INCLUDES=-Isrc -I$(DESTDIR)/usr/include
SRCS_CPP=$(shell find src -name "*.cpp")
SRCS_C=$(shell find src -name "*.c")
TARGET=$(DIST)/$(NAME)
LDFLAGS=-L$(DESTDIR)/usr/lib
# These are just examples
LDLIBSOPTIONS=\
-ldl \
-lz \
-ljson \
-lssl \
-lcrypto \
-lpthread
OBJ=\
$(addprefix $(BUILD)/,$(patsubst %.cpp,%.cpp_o,$(wildcard $(SRCS_CPP)))) \
$(addprefix $(BUILD)/,$(patsubst %.c,%.c_o,$(wildcard $(SRCS_C))))
MAKEFILE_INCLUDE=\
$(addprefix $(BUILD)/,$(patsubst %.cpp,%.cpp_o.d,$(wildcard $(SRCS_CPP)))) \
$(addprefix $(BUILD)/,$(patsubst %.c,%.c_o.d,$(wildcard $(SRCS_C))))
all: build
modules: $(MODULES)
build: $(TARGET)
@[ ! -e dist/last ] || rm dist/last
@ln -s $(CROSS)$(CONF) dist/last
$(TARGET): $(OBJ) $(DIST)
# For a binary
$(CXX) -o $(TARGET) $(CXXFLAGS) $(OBJ) $(LDLIBSOPTIONS)
# For a shared library
# $(CXX) -shared -o $(TARGET) $(CXXFLAGS) $(OBJ) $(LDLIBSOPTIONS)
-include $(MAKEFILE_INCLUDE)
$(BUILD)/%.cpp_o: %.cpp $(BUILD)
$(CXX) -c -o $@ $(CXXFLAGS) $(WARNING) $(INCLUDES) $(DEFINES) $<
$(CXX) -MM -o $@.d -MT $@ $(CXXFLAGS) $(WARNING) $(INCLUDES) $(DEFINES) $<
$(BUILD)/%.c_o: %.c $(BUILD)
$(CC) -c -o $@ $(CFLAGS) $(WARNING) $(INCLUDES) $(DEFINES) $<
$(CC) -MM -o $@.d -MT $@ $(CFLAGS) $(WARNING) $(INCLUDES) $(DEFINES) $<
build: $(BUILD)
$(BUILD): Makefile
# We create the same directories we have in "src" in "build"
find src -type d -exec mkdir -p $(BUILD)/{} \;
touch $(BUILD)
$(DIST):
mkdir -p $(DIST)
# Test this with: make install DESTDIR=./install PREFIX=/
install: build Makefile
# Binaries
[ -d $(DESTDIR)$(PREFIX)/bin ] || mkdir -p $(DESTDIR)$(PREFIX)/bin
cp dist/last/$(NAME) $(DESTDIR)/bin/$(NAME)
clean:
rm -Rf build dist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment