Post

Makefile build system

Makefile build system

As an applications grow, managing project structure and source files becomes more complex. Builds system are designed to help organize the development process and make software easier to build across different environments and infrastructures.

Makefile has become popular engineering tools for building system especially c/c++ and assembly. Developed as part of the GNU Project, Makefile enables developers to automate compilation and manage dependencies efficiently.

🗃️ Basic structure

A Makefile is made of rules:

1
2
target: dependencies
<TAB> command
  • target what you want to build (program)
  • dependencies files it depends on
  • command shell command to create the target (must start with TAB)

Example

1
2
hello:
	echo "Hello, world!"

run it command below, the output will be Hello, world!

1
$ make hello

💡 Concept rules

Variable

Used to avoid repetition and improve maintainability.

1
2
3
4
5
CC = gcc
CFLAGS = -Wall -O2

app: main.c
	$(CC) $(CFLAGS) main.c -o app

Equivalent shell expansion:

1
$ gcc -Wall -O2 main.c -o app

Automatic

Special variables that represent parts of the rule.

1
2
3
4
5
app: main.o math.o
	gcc $^ -o $@

main.o: main.c
	gcc -c $< -o $@
  • $@ target name
  • $< first prerequisite (main.c)
  • $^ all prerequisites (main.o, math.o)

Pattern

% is a wildcard that matches the same stem (base filename) in both the target and prerequisite patterns.

1
2
%.o: %.c
	gcc -c $< -o $@
  • %.o wildcard string with extension .o or object file
  • %.c wildcard string with extension .c or C language file

Phony

Targets that do not represent actual files or directory on system. Instead, it acts explicitly as a command runner or script alias to execute specific recipes every time it is called.

1
2
3
4
.PHONY: clean

clean:
	rm -f *.o app

Example

Here is common workflow example file.

1
2
3
.
├── main.c
└── Makefile

main.c

1
2
3
4
5
6
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

Makefile

1
2
3
4
5
6
7
CC = gcc

app: main.c
	$(CC) main.c -o app

clean:
	rm -f app

Run make for build C file and make clean for delete it

1
2
$ make
$ make clean

🌐 Other build system

Makefile is useful for unix/linux project especially use it for linux kernel project too.

I’ve only covered a few basics in this blog post, so if you want to learn more you can read from Official GNU Makefile or Makefile Tutorial also you can try other popular build system for c/c++ and assembly project:

This post is licensed under CC BY 4.0 by the author.