Skip to main content

Basic Makefile for C projects

Updated 2 min readMarkdown

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 project
  • make all - Same as make
  • make -j$(nproc) - Build using all available CPU cores
  • make clean - Remove build/ and the output binary
  • make rebuild - Clean everything and rebuild

No comments yet. Be the first to comment.