UNIX & GNU/Linux - make - Makefile

A Makefile has to be named Makefile with the first letter in capitalize.

There can be only one such file.
It is called with the make tool.
To use it simply write make on your terminal and it will execute the rules in your Makefile.

Using a Makefile is really helpful.
It automates tasks you have to do.
Let us take some examples:

In this first example, the Variables section contains 3 variables.

  • NAME gives a name to our executable (the traditional a.out becomes now gogogo);
  • SRC specifies all files with the .c extension that we want to compile together;
  • OBJ transforms all .c in .o.

For the second example we add some options for the compilation.

These options are found in the Variables section too.
The name of this variable is CFLAGS for Compilation Flags.
Sometimes, we don't need to add this variable on the rules.

The make tool will understand it.

But to be sure it will work, we add it.

So we add -Wall that will help us to enable all warnings that some people think that it would be a problem of compilation.

It add also certain warnings for C++ and Objective-C/C++.

To ensure that the warnings will be considered as errors, just add the -Werror flag.
To enable some more extra warnings, just add the -Wextra flag.
To enable a valid ISO C and C++ compilation, we have to use the -pedantic flag.

A few rare programs will require the -ansi or -std option for a correct version of ISO C.
But certain warnings must be enabled individually.
All rules on the GNU GCC's official website.

The LDFLAGS variable is for the Library Directory FLAGS.
We can compile our program with libraries of our choice.
But this time we have to specify it in our variables.

## example 1 of Makefile
## Made by BadproG.com

NAME    = gogogo
SRC     = main.c
OBJ     = $(SRC:.c=.o)

$(NAME) : $(OBJ)
	$(CC) $(OBJ) -o $(NAME) $(CFLAGS)
all     : $(NAME)
clean   :
	rm -f $(OBJ)
fclean  : clean
	rm -f $(NAME)

## example 2 of Makefile
## Made by BadproG.com

## Variables
NAME    = gogogo
SRC     = main.c begin.c ending.c
OBJ     = $(SRC:.c=.o)
CFLAGS  = -Werror -Wall -Wextra -pedantic -ansi
LDFLAGS = -L/path/until/yourlib -lyourlib

## Rules
$(NAME) : $(OBJ)
        $(CC) $(OBJ) -o $(NAME) $(CFLAGS) $(LDFLAGS)
all     : $(NAME)
clean   :
        rm -f $(OBJ)
fclean  : clean
        rm -f $(NAME)
re       : fclean all

If you have this error when compiling:

Makefile:15: *** missing separator (did you mean TAB instead of 8 spaces?).  Stop.

Just replace spaces by a tab at lines specified in the error.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.