How to Compile Multiple C Programs with a Single Makefile
This tutorial shows how to write a concise Makefile that automatically discovers all .c files in a directory, builds each into an executable with matching names, and supports easy addition of new programs with a single make command.
This guide presents a lightweight Makefile suitable for small practice projects where multiple C source files reside in the same folder and each should be compiled into its own executable.
Use case
The Makefile is intended for learning scenarios rather than large‑scale enterprise builds. When experimenting with short examples—often a single .c file per program—writing a separate Makefile for each file becomes cumbersome, and manually typing gcc commands slows down learning.
The desired workflow is to place several .c files in one directory and, with a single make invocation, compile all of them. Adding new source files should require no changes to the Makefile.
Design idea
Treat every .c file as an independent program; the resulting executable name matches the source filename without the .c suffix (e.g., app1.c → app1).
Use pattern rules to avoid writing repetitive compile commands.
Key Makefile fragments
Discover source files and derive target names:
SOURCE = $(wildcard *.c)
TARGETS = $(patsubst %.c, %, $(SOURCE))Compile each target with a generic pattern rule:
$(TARGETS): %: %.c
$(CC) $< $(CFLAGS) -o $@Full Makefile (including clean target):
SOURCE = $(wildcard *.c)
TARGETS = $(patsubst %.c, %, $(SOURCE))
CC = gcc
CFLAGS = -Wall -g
all: $(TARGETS)
$(TARGETS): %: %.c
$(CC) $< $(CFLAGS) -o $@
.PHONY: clean all
clean:
-rm -rf $(TARGETS)Running make builds all executables; make clean removes them.
Result
After compilation, the directory contains the generated binaries alongside the original .c files, as illustrated by the accompanying screenshot.
For the complete Makefile source, reply with mk2 to the original WeChat public account.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
