Skip to content

Instantly share code, notes, and snippets.

@liviaerxin
Created May 9, 2021 13:26
Show Gist options
  • Save liviaerxin/3ae9199546fee97c0468fab7db0fb126 to your computer and use it in GitHub Desktop.
Save liviaerxin/3ae9199546fee97c0468fab7db0fb126 to your computer and use it in GitHub Desktop.
Makefile Template for Small/Middle-Sized C Project

from How to write a Makefile with separate source and header directories?

c project directory structure like,

.
├── include
│   └── all .h files
├── lib
│   └── all third-party library files (.a/.so files) here
├── src
│   └── all .c files here
└── Makefile
INC_DIR   := include
SRC_DIR   := src
OBJ_DIR   := obj
BUILD_DIR := build

EXE := $(BUILD_DIR)/hellomake
SRC := $(wildcard $(SRC_DIR)/*.c)
OBJ := $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o)

CPPFLAGS := -I${INC_DIR} -MMD -MP
CFLAGS   := -Wall
LDFLAGS  := -Llib
LDLIBS   := -lm

.PHONY: all clean

all: $(EXE)

$(EXE): $(OBJ) | $(BUILD_DIR)
    $(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c | $(OBJ_DIR)
    $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

$(BUILD_DIR) $(OBJ_DIR):
    mkdir -p $@

clean:
    @$(RM) -rv $(BIN_DIR) $(OBJ_DIR)

-include $(OBJ:.o=.d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment