Makefile Tutorial
This article will explain what Make is, why it’s used, what is its alternative(s) and how to use makefiles in 7 modules. These modules will go from simple to complicated — I’ll try to make sure offering a comprehensive understanding of makefiles. Especially if you are a starter, I have no doubt you’ll learn a lot. Here are the source codes
First things first, Make is a script automatization technique invented by Stuart Feldman back in 70’s when working at Bell Labs. Just as Fertile Crescent is seen as the cradle of civilizations, Bell Labs is the cradle of computer science. UNIX (which will later be Torvald’s inspirer), C/C++ are all inventions of people from there. It is used in UNIX environments (Linux&Mac).
Get Buğrahan Karamollaoğlu’s stories in your inbox
Join Medium for free to get updates from this writer.
Make comes built-in in UNIX and here is how to check your Make version
make -v
GNU Make 4.3
Built for x86_64-pc-linux-gnu
Copyright (C) 1988-2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.It is primarily used to compile (mostly) C/C++ source codes en masse and generating an output file. Compiling a C/C++ file is normally quite easy with mere use of terminal
gcc -Wextra main.c -o mainBut what if we need to compile dozens of .c file if not hundreds at once? Writing the name of each file is of course not the way to go, so here we are aided by Makefiles. Let’s compile our main.c file using makefile .
Example One — Basics
First we need to create a file called Makefile, makefile or GNUmakefile. All three will be seen as a valid makefile by your OS but ‘Makefile’ is almost always used. You can use make -f command to choose any other file as your makefile but that is way too detail. Our makefile will suffice to look like this
CC = gcc # fun fact! if you don't specify, default compiler is cc
all: program
program: main.c
${CC} main.c -o program # this line is the purpose of the whole file
clean:
rm -rf programLet’s analyze our makefile
- We have a
variableCC . Lines used with (=) operator are called variables in a makefile. It’ll later be enough to say ${CC} (or $(CC) or $CC) to mean ‘gcc’. - We have also
commands. Lines used with (:) are called commands. They will later be used with commandmaketo execute different sorts of execution blocks. What you write after a command is calleddependency. A dependency, by its nature, is bound to its command. Make makes sure the dependency(ies) of a command is executed before executing the command itself. In our example, commandprogramis executed before running commandall. Similarly, commandprogramis executed only after Make checks a) there is a file named main.c b) there are some changes in thismain.c. This solves a problem calledrelink, which I will later dive into. - Command
cleanworks when user wants to clean the main.out file and go back to the initial status of the project.
If you want to execute a certain command, type it after keyword Make. i.e:
make clean
make myCommand …
! just saying <make> always executes automatically <make all> !
Then, we need to put our main.c file in the same directory, ready to be compiled with the command make.
Example Two —Multiple Files
Imagine we have three .c files:
- main.c
int main()
{
printf("%d\n", ft_strlen("bugra"));
ft_putchar('c');
ft_putchar('\n');
}- file1.c
int ft_strlen(char *str)
{
int i = 0;
while (str[i])
i++;
return i;
}- file2.c
void ft_putchar(char c)
{
write(1, &c, 1);
}Now, normally — we’d compile these like
gcc file1.c file2.c main.c -o programBut no need for verbosity when makefiles are cut out tools for the job
CC = gcc
CFLAGS = -Wall -Werror
all: program
program: main.c file1.c file2.c
$(CC) main.c file1.c file2.c -o program
clean:
rm -f programThe gist of above makefile is the indirectional command hierarchy and dependencies. By declaring main.c, file1.c and file2.c as dependencies for the command program, we are avoiding what is called relink, which occurs when users are able executemake again and again though no changes made in the files — which is something we don’t want. By building an indirectionate relation, changes are always checked before execution of main make command.
Example Three - Source Files under a Variable
By fetching source files from a directory, we don’t have to write name of each file
CC = gcc
SRC_DIR = src
# directory where .o files will be extracted to
OBJ_DIR = obj
SRC_FILES = $(wildcard $(SRC_DIR)/*.c)
# or you could say
# SRC_FILES = $(shell ls $(SRC_DIR)/*.c)
OBJ_FILES = $(patsubst $(SRC_DIR)/%.c, $(OBJ_DIR)/%.o, $(SRC_FILES))
all: program
program: $(OBJ_FILES)
$(CC) -o program $(OBJ_FILES)
@echo "\033[32mCompiled ✅\033[0;37m"
# -p means ignore parent directory if extant
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
mkdir -p $(OBJ_DIR)
$(CC) -c $< -o $@
clean:
@echo "\033[0;31mCleaning objects🧹"
rm -rf program $(OBJ_DIR)
fclean: clean
@echo "\033[0;31mRemoving $(NAME) 🗑\033[0;37m"Let’s analyze this makefile
- We first defined two directories : SRC_FILES, from which to take source files and OBJ_DIR, in which the .out files will be written
- $(OBJ_DIR)/%.o : puts all files ending with .o in the OBJ_DIR/ directory
- $< -o $@ : these are called automatic variables and are used as shortcuts. For instalce $< refers to the first dependency in the rule and $@ to the target of the file, in here
program
# most important automatic variables in makefile are below
$@ denotes the target (file that rule updates or creates)
$< denotes the first dependency of a rule
$^ denotes all the dependencies of a rule
$? denotes all the dependencies newer than the targetExample Four - Phony
We also have another conventional feature: phony
CC = gcc
CFLAGS = -Wall -Werror
all: program
program: main.c file1.c file2.c
$(CC) main.c file1.c file2.c -o program
clean:
rm -f program
.PHONY: all clean
We said that using make with a command name executes that spesific command. But what if user has a file with the same name of one of the commands? That’s what phony exists for. By adding this line, you can safely use make all and make clean without worrying there are files with such names
Example Five — Conditions
You can also use conditions in your makefile for spesific situations
CC = gcc
CFLAGS = -Wall
SRC_DIR = src
INC_DIR = include
OBJ_DIR = obj
# if it is debugged, compile with -g flag
DEBUG ?= 0
ifeq ($(DEBUG), 1)
CFLAGS += -g
@echo asdasdasd
endif
SRC_FILES = $(wildcard $(SRC_DIR)/*.c)
OBJ_FILES = $(patsubst $(SRC_DIR)/%.c, $(OBJ_DIR)/%.o, $(SRC_FILES))
all: program
program: $(OBJ_FILES)
$(CC) -o program $(OBJ_FILES)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
mkdir -p $(OBJ_DIR)
$(CC) -I$(INC_DIR) -c $< -o $@
clean:
rm -rf program $(OBJ_DIR)
fclean: clean
rm -rf programIf user decides to use this makefile under debug mode, he should say
make DEBUG=1Example Six — Implicit Rules
Implicit rules are rules that you imply the make to do the job by setting predefined dependencies and targets, all without writing user-defined, explicit rules
CC = gcc
SRCS = main.c file1.c file2.c
OBJS = $(SRCS:.c=.o)
all: program
program: $(OBJS)
$(CC) $(OBJS) -o program
# that is implicit rule
%.o: %.c
$(CC) -c $< -o $@
re: clean all
clean:
rm -f program
rm -f *.oThat way makefile automatically generates .o files from .c files without user having to write a compiling command
Example Seven — Wildcards
You can use a keyword called wildcard that will comprehense your multiple files at once
SRCS = main.c file1.c file2.c # ya da
SRCS = $(wildcard *.c)
OBJS = $(SRCS:.c=.o)
all: program
program: $(OBJS)
$(CC) $(OBJS) -o program
%.o: %.c
$(CC) -c $< -o $@
re: clean all
# mesela *.o demek .o ile bütün her şey demektir
clean:
rm -f *.oThat way it will count all the files that end with .c. This is actually a bash technique frequently used with makefiles for it makes things much easier and code less shorter.
There are still hundreds of more features and details to these, these are just what I generally use if I can’t convince AI to write a makefile for me. Here is my makefile notes and in it you’ll find some (probably much better) sources I benefited for this article
bye!









