How to use Makefile

Jun 10, 2023

Makefile

Simple Makefile rule:

1
2
target ...: prerequisites ...
command
  • target is the target file, it can either be an Object File, or Executable File, even can be a Label.

  • prerequisites is files or objs to generate the target.

  • command is the command to eval.

It is the relationship about files execution. That is to say, target depends on prerequisites, and the generation rule is at command. More conciselly to say, prerequisites has more than one file changed, command is about to executes. This is the signification of the Makefile.

Sample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// hellofunc.c
#include <stdio.h>
#include <hellomake.h>

void myPrintHelloMake() {
printf("Hello, make files!\n");
}

// hellomake.h
void myPrintHelloMake();

// hellomake.c
#include <hellomake.h>
int main() {
myPrintHelloMake();
return 0;
}

Let’s write Makefile:

1
2
3
4
5
6
7
8
9
10
CC=gcc
edit : hellofunc.o hellomake.o
$(CC) -o edit hellofunc.o hellomake.o
hellofunc.o : hellofunc.c
$(CC) -c hellofunc.c -I.
hellomake.o : hellomake.c
$(CC) -c hellomake.c -I.
clean:
rm hellofunc.o /
hellomake.o

Symbol $(CC) replace with gcc, symbol / the same as \r\n. After input make at terminal, middle and final files generated. If you want to delete *.o and edit, just eval make clean at terminal.

After defining the dependencies between files, the command defined how to generate target file by system command call, the command must start with a Tab key. make will compare time between target file and prerequisites files, calling the command when date of prerequisites is new to target‘s.

Pluz, clean in command make clean is not a command from make, it is a label in Makefile.

Use Parametric

We have use param in above sample, a more usefull sample:

1
2
3
4
5
6
7
8
9
10
CC=gcc
objects=hellofunc.o hellomake.o
edit : $(objects)
$(CC) -o edit $(objects)
hellofunc.o : hellofunc.c
$(CC) -c hellofunc.c -I.
hellomake.o : hellomake.c
${CC} -c hellomake.c -I.
clean:
rm edit $(objects)

This will save more time by only change the objects field.

Makefile filename

Typically, make command will search unrecursively by sort: GNUmakefile / makefile / Makefile. GNUmakefile is for GNU only, so Makefile is recommanded for eye-catching by first letter uppercase.

You can use other filenames, such as Makefile.linux / Makefile.win etc. If filename is specificlly created, you can use -f or --file to specify the target file: make -f Makefile.win.