C++ - Makefile - Adding flags

A personal Makefile is sometimes better than a Makefile generated by default by your IDE, such Eclipse or Visual Studio C++ for example.

If you don't know how to create one, let's see it in this easy example of Makefile for C++.
I added some flags for the variable CXXFLAGS, it is different from the C language, where it is CFLAGS.

With g++, you do not have to write the variable CXXFLAGS in your compilation line, but if you prefer, you can add it.

## Variables
NAME    = goooooooooo
SRC     = main.cpp parent.cpp child.cpp
OBJ     = $(SRC:.cpp=.o)
CXXFLAGS  = -Wall -Werror -Wextra -pedantic -ansi
CC        = g++

## Rules
$(NAME) : $(OBJ)
    $(CC) $(OBJ) -o $(NAME)
all     : $(NAME)
clean   :
    rm -f $(OBJ)
fclean  : clean
    rm -f $(NAME)
re    : fclean all
r    : re
    rm -f *~
    rm -f *.o

If you have a personal library that you created, add the LDFLAGS variable in the compilation line, like this:

## Variables
NAME    = goooooooooo
SRC     = main.cpp parent.cpp child.cpp
OBJ     = $(SRC:.cpp=.o)
CXXFLAGS  = -Wall -Werror -Wextra -pedantic -ansi
CC        = g++
LDFLAGS = -L/path/until/yourlib -lyourlib

## Rules
$(NAME) : $(OBJ)
    $(CC) $(OBJ) -o $(NAME) $(LDFLAGS)
all     : $(NAME)
clean   :
    rm -f $(OBJ)
fclean  : clean
    rm -f $(NAME)
re    : fclean all
r    : re
    rm -f *~
    rm -f *.o

If you have this error when you tried the example above:

Makefile:10: *** missing separator.  Stop.

It is because you have copy / paste it.
Just replace the space by a tab and it will be fine.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.