Skip to content

Instantly share code, notes, and snippets.

@leostera
Forked from shreyassanthu77/Makefile
Created December 19, 2024 13:06
Show Gist options
  • Save leostera/00fd2e493bbe4dca2ae31fea5f42489a to your computer and use it in GitHub Desktop.
Save leostera/00fd2e493bbe4dca2ae31fea5f42489a to your computer and use it in GitHub Desktop.
src_dir ?= src
build_dir ?= build/
main ?= main
mode ?= debug
arch ?= $(shell uname -m)
os ?= $(shell uname -s | tr '[:upper:]' '[:lower:]')
ifeq ($(os), linux)
abi = musl
else ifeq ($(os), windows)
abi = gnu
else
$(error Unsupported OS)
endif
target ?= $(arch)-$(os)-$(abi)
cflags = -Wall -Wextra -Werror -std=c23
ifneq ($(shell which zig 2>/dev/null),)
cc = zig cc -target $(target)
else
$(error Zig is not installed or not available on the system)
endif
ifeq ($(mode), debug)
cflags += -g -O0
else ifeq ($(mode), release)
cflags += -O2 -s
else ifeq ($(mode), release-fast)
cflags += -O3 -s
else ifeq ($(mode), release-small)
cflags += -Oz
else
$(error Unknown build mode)
endif
obj_dir = $(dir $(build_dir))/$(target)/$(mode)/obj
bin_dir = $(dir $(build_dir))/$(target)/$(mode)
SRC_FILES = $(shell find $(src_dir) -type f -name "*.c")
OBJ_FILES = $(patsubst $(src_dir)/%.c, $(obj_dir)/%.o, $(SRC_FILES))
.PHONY: build
build: $(OBJ_FILES) $(bin_dir)/$(main)
.PHONY: help
help:
@echo "Available targets:"
@echo " build : Build the project (default)"
@echo " clean : Clean the build directory"
@echo " help : Display this help message"
@echo ""
@echo "Build modes:"
@echo " debug : Build with debug symbols and no optimization"
@echo " release : Build with optimization level 2 and no debug symbols"
@echo " release-fast : Build with optimization level 3 and no debug symbols"
@echo " release-small : Build with size optimization and no debug symbols"
@echo ""
@echo "Variables:"
@echo " src_dir : Specify the source directory (default: src)"
@echo " build_dir : Specify the build directory (default: build/)"
@echo " main : Specify the main executable name (default: nisi)"
@echo " mode : Specify the build mode (default: debug)"
@echo " os : Specify the target OS (default: your OS)"
@echo " abi : Specify the target ABI (default: musl on Linux, gnu on Windows)"
@echo " arch : Specify the target architecture (default: your arch)"
@echo " target : Specify the target triple (default: arch-os-abi)"
$(obj_dir)/%.o: $(src_dir)/%.c
@mkdir -p $(dir $@)
$(cc) $(cflags) -c $< -o $@
$(bin_dir)/$(main): $(OBJ_FILES)
@mkdir -p $(dir $@)
$(cc) $(cflags) $^ -o $@
.PHONY: clean
clean:
rm -rf $(build_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment