Skip to content

Instantly share code, notes, and snippets.

@rafaelrc7
Created December 10, 2023 22:11
Show Gist options
  • Save rafaelrc7/431c2973cd52014b178bfbebe9d95a50 to your computer and use it in GitHub Desktop.
Save rafaelrc7/431c2973cd52014b178bfbebe9d95a50 to your computer and use it in GitHub Desktop.
Generic Makefile for c/cxx/asm and nix
TARGET := a.out
CXX := g++
CC := gcc
AS := as
LD := $(CXX)
DEBUGFLAGS ?= -DDEBUG -ggdb -O0 -U_FORTIFY_SOURCE
RELEASEFLAGS ?= -DNDEBUG -O2
COMMONFLAGS ?= -flto -Wall -Wextra -pedantic -Werror=vla
CXXFLAGS ?= -std=c++17
CFLAGS ?= -std=c17
ASFLAGS ?=
LDFLAGS ?= -flto=auto
SRC_DIR := ./src
BUILD_DIR := ./build
BIN_DIR := ./bin
all: release
########################## DONT EDIT BELOW THIS LINE ##########################
.PHONY: all debug release clean compiledb run
SRCS := $(shell find $(SRC_DIR) -name *.c -or -name *.cpp -or -name *.s)
OBJS := $(SRCS:%=$(BUILD_DIR)/%.o)
DEPS := $(OBJS:.o=.d)
INC_DIRS := $(shell find $(SRC_DIR) -type d)
INC_DIRS_FLAGS := $(addprefix -I,$(INC_DIRS))
BUILD_SRC_DIRS := $(addprefix $(BUILD_DIR)/,$(SRC_DIR))
debug: CXXFLAGS += $(DEBUGFLAGS)
debug: CFLAGS += $(DEBUGFLAGS)
debug: $(BIN_DIR)/$(TARGET)
release: CXXFLAGS += $(RELEASEFLAGS)
release: CFLAGS += $(RELEASEFLAGS)
release: LDFLAGS += -s
release: $(BIN_DIR)/$(TARGET)
# Target executable
$(BIN_DIR)/$(TARGET): $(OBJS) | $(BIN_DIR)
$(LD) $(OBJS) -o $@ $(LDFLAGS)
# C object files
$(BUILD_DIR)/%.c.o: %.c | $(BUILD_SRC_DIRS)
$(CC) $(CFLAGS) $(COMMONFLAGS) $(INC_DIRS_FLAGS) -c $< -o $@
# C++ object files
$(BUILD_DIR)/%.cpp.o: %.cpp | $(BUILD_SRC_DIRS)
$(CXX) $(CXXFLAGS) $(COMMONFLAGS) $(INC_DIRS_FLAGS) -c $< -o $@
# Assembly object files
$(BUILD_DIR)/%.s.o: %.s | $(BUILD_SRC_DIRS)
$(AS) $(ASFLAGS) -c $< -o $@
# C header depdency files
$(BUILD_DIR)/%.c.d: %.c | $(BUILD_SRC_DIRS)
@$(CC) $(CFLAGS) $(COMMONFLAGS) $(INC_DIRS_FLAGS) $< -MM -MT $(@:%.c.d=%.c.o) >$@
# C++ header depdency files
$(BUILD_DIR)/%.cpp.d: %.cpp | $(BUILD_SRC_DIRS)
@$(CXX) $(CXXFLAGS) $(COMMONFLAGS) $(INC_DIRS_FLAGS) $< -MM -MT $(@:%.cpp.d=%.cpp.o) >$@
# Directories
$(BUILD_DIR) $(BUILD_SRC_DIRS) $(BIN_DIR):
@$(MKDIR_P) $@
compiledb: compile_commands.json
compile_commands.json: Makefile flake.nix shell.nix default.nix flake.lock
bear -- make -B
clean:
$(RM_R) $(BUILD_DIR) $(BIN_DIR)
-include $(DEPS)
MKDIR_P ?= mkdir -p
RM_R ?= rm -r
run: $(BIN_DIR)/$(TARGET)
$(BIN_DIR)/$(TARGET)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment