DEV Community

Slava "nerfur" Voronzoff
Slava "nerfur" Voronzoff

Posted on

Easy make and Makefile for beginners

make is one of the most important tools in programming. Both in past and present days. But also pretty scary, because many beginners see only Makefile from already established and big projects with huge amount of lines inside.

Don't be afraid! Basic Makefile is pretty easy after this short "trick".

For example let's imagine you have command line to compile your little C code like this:

gcc -I/usr/local/include -L/usr/local/lib -Wall -o my-c-app.out my-c-app.c

just open your favorite text editor and paste this command inside

now you just need to split it to sort of variables for make, you can choose names you want (there are some common practices, btw)
let's split it

CC = gcc

OBJECTS = my-c-app.c

OBJECT_OUT = my-c-app.out

CFLAGS = -Wall

INCLUDES = -I/usr/local/include -L/usr/local/lib

and swap values in your command with this variables

$(CC) $(INCLUDES) $(CFLAGS) -o $(OBJECT_OUT) $(OBJECTS)

and last touch - we need to add target for make - default one is all

so we transform our command line to
all: $(OBJECTS)
$(CC) $(INCLUDES) $(CFLAGS) -o $(OBJECT_OUT) $(OBJECTS) (this line always MUST start with Tab !!!)

so, now we have file like this

CC = gcc

OBJECTS = my-c-app.c

OBJECT_OUT = my-c-app.out

CFLAGS = -Wall

INCLUDES = -I/usr/local/include -L/usr/local/lib

all: $(OBJECTS)
    $(CC) $(INCLUDES) $(CFLAGS) -o $(OBJECT_OUT) $(OBJECTS)

now you can run make and enjoy beginning of your dive to Makefile magic!

Good Luck!

Top comments (0)