Build Automation with make: Rules, Targets & Makefiles
Build Automation with make: Rules, Targets & Makefiles
This page introduces build automation with the `make` tool, which simplifies and automates compiling and linking assembly or C programs.
Why build automation?
Large programs consist of many files and dependencies. Building each file manually with assembler and linker commands becomes repetitive and error-prone.
Build automation tools solve this problem by:
- Automating the steps required to build software.
- Rebuilding only changed parts, saving time.
- Maintaining consistency across large projects.
In the world of C, C++, and assembly, the traditional build tool is **make**. For Java projects, similar tools include Ant, Maven, and Gradle.
What make does
make reads rules that define:
- Which files depend on which other files (dependencies).
- What commands are required to build a given target.
Each rule has three components: 1. **Target** – the file to be built (e.g., an executable). 2. **Prerequisites** – files required to build the target (e.g., object files). 3. **Command** – the shell command(s) to build the target.
Syntax: ```
target [target ...]: [prerequisite ...] <TAB> [command]
``` Note: indentation must use a **TAB** character, not spaces.
Example: eatsyscall64 makefile
For the assembly example, we can automate the build as follows:
```
eatsyscall64: eatsyscall64.o ld -o eatsyscall64 eatsyscall64.o
eatsyscall64.o: eatsyscall64.asm nasm -f elf64 -g -F dwarf eatsyscall64.asm -o eatsyscall64.o -l eatsyscall64.lst
```
Explanation:
- The first rule builds the executable `eatsyscall64` from its object file.
- The second rule assembles the source file into the object file.
- The `-l eatsyscall64.lst` option creates a listing file for debugging.
File naming and execution
By default, make looks for a file named `Makefile`, `makefile`, or `GNUmakefile` in the current directory.
If you simply run: ```
make
``` make builds the first target it finds in the makefile. To build a specific target: ```
make eatsyscall64
```
Clean target
It is good practice to include a **clean** target to delete generated files: ```
clean: rm -f eatsyscall64 eatsyscall64.o eatsyscall64.lst
```
Now you can type: ```
make clean
``` to remove all build artifacts.
Benefits of make
- Automates repetitive commands.
- Detects which files have changed since the last build and rebuilds only those.
- Keeps projects consistent and organized.
- Easily extended with variables, patterns, and multiple targets for complex systems.
Beyond the basics
make can do much more:
- Define variables for compiler options.
- Use wildcard patterns to apply one rule to many files.
- Chain multiple makefiles for large software projects.
These advanced features are introduced later in the course, but the fundamentals shown here are enough for small assembly programs.