Using the Make tool and creating makefiles for C
According with [1] is a Unix tool that simplifies to build a program executables like C, C++, LaTeX, among others. The make application reads and follows the rules inside a Makefile
. Each rule is known as a target and we are going to learn how to create our own Makefile
for basic projects like a C project compiled with GCC.
Writing a basic Makefile
Let’s star with a simple project you must need a C file and the Makefile. Thus, the contents of your C file could be something like this:
#include <stdio.h>
int main(){
printf("Version 0.1\n");
return 0;
}
Now let’s create the makefile with two simple targets all and clean:
#Builds an executable called out from the main.c source:
all: main.c
gcc -g -Wall -o out main.c
clean:
rm out
Now you can just call the make
command on the terminal and the by using:
$ make all
then, you will obtain the out file in the current directory (check it using ls
). Then, if you want to clean your working directory just type:
$ make clean
rm out
$ ls -l
total 3
-rw-rw-r-- 1 gmarx gmarx 73 jun 10 16:44 main.c
-rw-rw-r-- 1 gmarx gmarx 114 jun 10 16:49 Makefile
-rw-rw-r-- 1 gmarx gmarx 0 jun 9 00:37 Readme.md
Just considers that a general target entry should looks like:
# this is a comment
target: dependency1 dependency2 ... dependencyN
<TAB> command
note: the in the makefile is necessary as part of the syntax, otherwise the target will not work
A more general makefile
Now we can create a more general rule/target for C files by defining some variables:
# Builds all *.c source files creating outpufiles with the same name as the original file
CC = gcc
# flags
# -g for debuging
# -Wall turn on compiler warnings
CFLAGS = -g -Wall
# The taget executable:
TARGET = main
all: $(TARGET)
$(TARGET): $(TARGET).c
$(CC) $(CFLAGS) -o $(TARGET) $(TARGET).c
clean:
$(RM) $(TARGET)
Note: if you need to build more files you should use a recursive way (wildcard function
Then, let’s execute the makefile only using make
command:
$ make
gcc -g -Wall -o main main.c
$ ls -l
total 36
-rwxrwxr-x 1 gmarx gmarx 19176 jun 10 17:12 main
-rw-rw-r-- 1 gmarx gmarx 73 jun 10 16:44 main.c
-rw-rw-r-- 1 gmarx gmarx 325 jun 10 17:11 Makefile
-rw-rw-r-- 1 gmarx gmarx 0 jun 9 00:37 Readme.md
$ make clean
rm -f main
$ ls -l
total 16
-rw-rw-r-- 1 gmarx gmarx 73 jun 10 16:44 main.c
-rw-rw-r-- 1 gmarx gmarx 325 jun 10 17:11 Makefile
-rw-rw-r-- 1 gmarx gmarx 0 jun 9 00:37 Readme.md
OK, thats all. I hope this can be useful for you. Later, I will post a more complex makefiles for recursive and libraries integration.