Last active
April 10, 2020 14:49
-
-
Save ngquerol/8c780e8eb0813b18ba1c29c0ab96561e to your computer and use it in GitHub Desktop.
Generic Makefile for simple C projects, supporting compilation databases via Clang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Variables (all configuration should happen here) | |
SHELL = /bin/sh | |
CC = clang | |
CFLAGS = -Wall -Wextra -Wpedantic -std=c99 | |
LDFLAGS = | |
RELEASE_CFLAGS = -Os | |
DEBUG_CFLAGS = -g -O0 -DDEBUG | |
RELEASE_LDFLAGS = | |
DEBUG_LDFLAGS = | |
SOURCE_DIR = src | |
BUILD_DIR = build | |
SOURCES = $(wildcard $(SOURCE_DIR)/*.c) | |
OBJECTS = $(patsubst $(SOURCE_DIR)/%.c, $(BUILD_DIR)/%.o, $(SOURCES)) | |
EXECUTABLE = $(BUILD_DIR)/hello_world | |
COMPILATION_DATABASE_ENTRIES = $(addsuffix .json,$(OBJECTS)) | |
COMPILATION_DATABASE = compile_commands.json | |
# PHONY targets, i.e. not linked to a file | |
.PHONY: all run release debug compilation_db | |
all: release | |
run: ./$(EXECUTABLE) | |
release: CFLAGS += $(RELEASE_CFLAGS) | |
release: LDFLAGS += $(RELEASE_LDFLAGS) | |
release: $(EXECUTABLE) | |
debug: CFLAGS += $(DEBUG_CFLAGS) | |
debug: LDFLAGS += $(DEBUG_LDFLAGS) | |
debug: $(EXECUTABLE) | |
compilation_db: DEBUG_CFLAGS += -MJ [email protected] | |
compilation_db: clean $(OBJECTS) $(COMPILATION_DATABASE) | |
# File targets | |
$(BUILD_DIR): | |
@mkdir $(BUILD_DIR) | |
$(EXECUTABLE): $(OBJECTS) | |
$(info Linking executable "$@") | |
@$(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@ | |
$(BUILD_DIR)/%.o: $(SOURCE_DIR)/%.c | $(BUILD_DIR) | |
$(info Compiling object file "$@") | |
@$(CC) $(CFLAGS) -c $< -o $@ | |
$(COMPILATION_DATABASE): | |
$(info (Re)generating compilation database) | |
@sed -e '1s/^/[/' -e '$$s/,$$/]/' \ | |
$(COMPILATION_DATABASE_ENTRIES) > $@ | |
# Cleaning targets | |
.PHONY: clean mrproper | |
clean: | |
$(info Deleting object files) | |
@$(RM) $(OBJECTS) | |
@$(RM) $(COMPILATION_DATABASE_ENTRIES) | |
mrproper: clean | |
$(info Deleting build directory) | |
@$(RM) -r $(BUILD_DIR) | |
$(info Deleting compilation database) | |
@$(RM) $(COMPILATION_DATABASE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment