How to create a simple C++ Makefile

Remember to use “Tab” as a separator.
Set the name of the final binary file for the program.
TARGET = test_functions
$(TARGET) is the way to dereference the content of the variable.
Set compiler flags for #include directories so that compiler knows where to look for header files. The directory paths used are relative to the current one.

CFLAGS = -O3 -I src/boost -I src/ublas -I src -Wall

-Wall option turns on warning messages.
library flags go here

LFLAGS =

$(CC) will mean a call to compiler program:

CC = g++

Save names of most common directories in variables:

TESTDIR = tests
SRCDIR = src

Specify location of source files

SRC = $(TESTDIR)/test_functions.cpp

To include more source files you can use, for example,

SRC += ../../src/alglibinternal.cpp

Substitute suffixes .cpp in $(SRC) with with .o and place new string with names into $(OBJ):

OBJ = $(SRC:.cpp=.o)

Create rule for compilation of the final binary. $(OBJ) refers to a list of *.o files obtained by compiling *.cpp files in below:

$(TARGET): $(OBJ)
@echo Linking $@
@$(CC) $(LFLAGS) $(OBJ) -o $@
@echo Build Complete

Create rule to compile *.o object files from *.cpp files

.cpp.o: $<
@echo Compiling $<
@$(CC) -c $(CFLAGS) $< -o $@

Create rule for 'make clean' command that will remove all products of previous compilations

clean:
@rm -f $(OBJ) $(TARGET)
@echo All object files and binaries removed

Below is the whole Makefile in one place:

TARGET = test_functions

# setting compiler flag for include directory by using relative to the current
# directory path
CFLAGS = -O3 -I src/boost -I src/ublas -I src -Wall

# library flags go here
LFLAGS =

CC = g++

TESTDIR = tests
SRCDIR = src

# specifying source files
SRC = $(TESTDIR)/test_functions.cpp
#SRC += ../../src/alglibinternal.cpp

# suffix .cpp in $SRC will be substitued to .o
OBJ = $(SRC:.cpp=.o)

# rule for creating the final binary. $OBJ is a list of *.o files obtained by compiling *.cpp files
$(TARGET): $(OBJ)
@echo Linking $@
@$(CC) $(LFLAGS) $(OBJ) -o $@
@echo Build Complete

# rule to compile *.o object files from *.cpp files
.cpp.o: $<
@echo Compiling $<
@$(CC) -c $(CFLAGS) $< -o $@

# rule for 'make clean' command
clean:
@rm -f $(OBJ) $(TARGET)
@echo All object files and binaries removed

Advertisements
This entry was posted in C++, Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s