Makefile Tutorial for Beginner – 1


At Linux Shell, a makefile is named Makefile or makefile. A makefile is a text file that defines rules to compile the source code. Without makefiles, you probably need several commands to build a project and worse, you don’t know which module requires re-compilation.

How does a makefile work?

Suppose, you have a very simple C source code, e.g. named test.c:

1
2
3
4
5
#include <stdio.h>
 
void main() {
        printf("%s\n", "HelloACM.com");
}
#include <stdio.h>

void main() {
        printf("%s\n", "HelloACM.com");
}

You can invoke GCC to compile the source code to binary:

1
gcc -o test test.c
gcc -o test test.c

The -o specifies the binary output. The above command will compile the source code into a binary test and you can execute the binary by

1
./test
./test

which will simply print out the message HelloACM.com

So let’s define the above compilation rules in a makefile. Use your favorite text editor e.g. vim/emacs and save the following Makefile

# In Makefile, comments start with #

# define constants
CC=gcc

# compile to binary test
test: test.c
        $(CC) -o test test.c

# delete the binary
clean: 
        rm -f test

So we can see, the # at each line starts with comments in a Makefile. We can define constants like CONST=VAL and use them later like $(CONST).

At this example, we define two targets which are test and clean. After the colon, you can put optionally the dependency. In the target test apparently the binary depends on the source code test.c.

The next line, starts with a TAB, followed by the action (command). So if you type make test in the command line, the Linux shell will look for the Makefile, and look for the target test. It then proceeds to the command defined next to it, which is $(CC) -o test test.c where $(CC) is further expanded with the actual constant value gcc. Similarly, if you type in make clean, it will execute rm -f test.

The good thing about makefile is that it will not compile the source code again if the dependency has not changed and the binary is up-to-date. Wait, if we specify a target, e.g. love, which isn’t defined yet, what would happen?

1
2
$ make love
make: *** No rule to make target `love'.  Stop.
$ make love
make: *** No rule to make target `love'.  Stop.

Here is a more ‘correct’ full version:

1
2
love:man.o woman.o
    ${CC} ${CFLAGS} ${LIB} man.o woman.o -o baby
love:man.o woman.o
    ${CC} ${CFLAGS} ${LIB} man.o woman.o -o baby

And all you need is:

make love && make install Click To Tweet

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
531 words
Last Post: C++ Coding Exericse - Tiny TimeIt Utility to Time the Applications
Next Post: How to Count Numbers with Unique Digits?

The Permanent URL is: Makefile Tutorial for Beginner – 1

Leave a Reply