Makefile:
# ==========================================
# Configuration
# ==========================================
CC := gcc
TARGET := hello
STD := c11
OPT := 2
CFLAGS := -std=$(STD) -O$(OPT) -Wall -Wextra -Wpedantic
CPPFLAGS := -Iinclude -MMD -MP
LDFLAGS :=
LDLIBS :=
BUILD := build
# ==========================================
# Source files
# ==========================================
SOURCES := $(wildcard *.c)
OBJECTS := $(patsubst %.c,$(BUILD)/%.o,$(SOURCES))
DEPS := $(OBJECTS:.o=.d)
# ==========================================
# Build rules
# ==========================================
.PHONY: all clean rebuild
all: $(TARGET)
# Link executable
$(TARGET): $(OBJECTS)
@echo " LINK $@"
@$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
# Compile individual source files
$(BUILD)/%.o: %.c | $(BUILD)
@echo " CC $<"
@$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
# Create build directory
$(BUILD):
@mkdir -p $@
# ==========================================
# Utilities
# ==========================================
clean:
@echo " CLEAN"
@rm -rf $(BUILD) $(TARGET)
rebuild: clean all
# ==========================================
# Header dependencies
# ==========================================
-include $(DEPS)
The project structure would be like this:
So, all .c files will be at the root of the project folder.
.h files will be in include folder.
All the output files like .o files will go to build folder.
The output binary will be created at the root of the project.
Make Commands
make- Build the projectmake all- Same as makemake -j$(nproc)- Build using all available CPU coresmake clean- Remove build/ and the output binarymake rebuild- Clean everything and rebuild
Comments
Join the discussionNo comments yet. Be the first to comment.



