So currently I am still working on the Amiga Tool Jam which I mentioned in my previous post Its Summer Time! ☀️ and I got introduced to something called Makefile.

What is Makefile?

Makefiles are a simple way to organize code compilation. It is a way of automating software building procedures and other complex tasks with dependencies.

I used Makefile for compiling my C code and it is really useful.

How to use Makefile?

First, you need to create a file called Makefile in your project directory.

Makefile is a file that tells Make what to do. You may have a file called hello.c and if you want to compile it to hello.o then you can use Makefile to do that.

hello.o: hello.c
    gcc -c hello.c

The above code is a simple Makefile that tells make to compile hello.c to hello.o using gcc.

Now if you wanted to make it into a executable file you can do this.

hello: hello.o
    gcc -o hello hello.o

Now you can run make hello in your terminal to compile your code.

The makefile is read by the make command, which determines which parts of a program need to be recompiled, and issues a command to recompile them.

What we created above is called a rule.

A rule appears in the makefile and says when and how to remake certain files, called the rule’s targets (most often only one per rule). It lists the other files that are the prerequisites of the target, and the recipe to use to create or update the target.

What is a recipe?

A recipe appears in the makefile and says what to do. It consists of shell commands, one per line, to carry out the rule’s prerequisites. The recipe lines start with a tab character not spaces.

What is a target?

A target is usually the name of a file that is generated by a program; examples of targets are executable or object files. A target can also be the name of an action to carry out, such as ‘clean’.

target … : prerequisites …
        recipe

What is a prerequisite?

A prerequisite is a file that is used as input to create the target. A target often depends on several files. The prerequisites will run first before the recipe is executed.

Let’s say we wanted to have 2 different rules in our Makefile. One for compiling and one for cleaning.

You would write the following:

hello.o: hello.c
    gcc -c hello.c

hello: hello.o
    gcc -o hello hello.o

clean:
    rm hello.o hello

Now you can run make clean to clean your project directory and use make hello to compile your code.

Makefile is extremely useful for compiling your code and it is really easy to use once you get the hang of it.

I highly recommend checking it out if you are interested. There is an amazing tutorial on Makefile at https://makefiletutorial.com/. Which goes more in-depth on how to use Makefile.

Hope you liked the post and Thanks so much for reading :D