This tutorial provides a step-by-step guide that covers the basics of makefiles. It was built on top of the Makefile Tutorial By Example, created by Chase Lambert, and the GNU Make Manual. The examples are available in separate folders. Each folder has a makefile containing code discussed in a README file. In the end, you'll see how various topics work together in an example project (see Makefile Cookbook).
- Basic knowledge of the compilation process in C
- Basic knowledge of bash scripting
gcc
andmake
installed- Git Bash installed, if using windows.
Makefiles are used to help decide which parts of a large program need to be recompiled. In the vast majority of cases, C or C++ files are compiled. Other languages typically have their own tools that serve a similar purpose as Make. Make can also be used beyond compilation too, when you need a series of instructions to run depending on what files have changed. This tutorial will focus on the C/C++ compilation use case.
Here's an example dependency graph that you might build with Make. If any file's dependencies changes, then the file will get recompiled:
Popular C/C++ alternative build systems are SCons, CMake, Bazel, and Ninja. Some code editors like Microsoft Visual Studio have their own built in build tools. For Java, there's Ant, Maven, and Gradle. Other languages like Go and Rust have their own build tools.
Interpreted languages like Python, Ruby, and Javascript don't require an analogue to makefiles. The goal of makefiles is to compile whatever files need to be compiled, based on what files have changed. But when files in interpreted languages change, nothing needs to get recompiled. When the program runs, the most recent version of the file is used.
There are a variety of implementations of Make, but most of this guide will work on whatever version you're using. However, it's specifically written for GNU Make, which is the standard implementation on Linux and MacOS. All the examples work for Make versions 3 and 4, which are nearly equivalent other than some esoteric differences.
- EX001 - Hello World
- EX002 - Makefile Syntax
- EX003 - Makefile Sequence of Events
- EX004 - Make clean
- EX005 - Variables
- EX006 - Automatic Variables
- EX007 - Targets
- EX008 - The Asterisk Wildcard
- EX009 - The Percent Sign Wildcard
- EX010 - Implicit Rules
- EX011 - Static Pattern Rules
- EX012 - Pattern Rules
- EX013 - Double-Colon Rules
- EX014 - Command Silencing
- EX015 - Command Execution
- EX016 - Default Shell
- EX017 - Double Dollar Sign
- EX018 - Error Handling
- EX019 - Recursion
- EX020 - Environment Variables
- EX021 - Override CLI Arguments
- EX022 - Functions
- EX023 - Conditional Statements
- EX024 - VPATH_ Search Path for All Prerequisites
- EX025 - Phony Targets
- Makefile Cookbook