Skip to content

Instantly share code, notes, and snippets.

@mihai-valentin
Last active June 28, 2024 13:53
Show Gist options
  • Select an option

  • Save mihai-valentin/f6da28fc1240778b783d7cd7e20352d4 to your computer and use it in GitHub Desktop.

Select an option

Save mihai-valentin/f6da28fc1240778b783d7cd7e20352d4 to your computer and use it in GitHub Desktop.
A simple Makefile recipe to compile a multi-file c program

Supported project structure:

project-root
|-- src
     |-- include # storage for header files
     |   |-- *.h
     |-- <any-sub-dir>
     |   |-- *.c
     |-- main.c

Use cases

Store the Makefile in the project root dir to use it.

Build and Run

make

Build

make build

Run

make run

How it works?

The Makefile declares dependencies between all "c" and "o" files. Once any "c" file changes, make will compile all the "o" files first and then the target executable. The target executable is stored under the dist directory.

All the temporary files will be created in the project root directory and deleted later by the clean goal.

You can customize source dir, dist dir, target name, and compiler flags by editing corresponding variables (SRC_DIR, DIST_DIR, TARGET, CFLAGS).

Have fun in development!

.DEFAULT_GOAL := all
.PHONY: all build clean run
SRC_DIR := ./src
DIST_DIR := ./dist
TARGET := main
CFLAGS := -Isrc/include
C_SRC := $(wildcard $(SRC_DIR)/*.c $(SRC_DIR)/**/*.c)
OBJECTS := $(patsubst %.c,%.o,$(notdir $(C_SRC)))
all: build run
build: $(TARGET) clean
run:
@$(DIST_DIR)/$(TARGET)
$(TARGET): $(OBJECTS)
mkdir -p $(DIST_DIR)
gcc -o $(DIST_DIR)/$@ $^ $(CFLAGS)
$(OBJECTS): $(C_SRC)
gcc -c $^ $(CFLAGS)
clean:
rm $(OBJECTS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment