Building with Make and Makefiles#

The make utility runs commands described in a file named Makefile. It is useful when a project has repeated build steps or several source files.

The current course syllabus, assignment instructions, programming standards, and applicable CSN or college policies take precedence over anything on this website.

Compiler environment variables#

On Bellagio, CXX and CXXFLAGS are predefined environment variables.

CXX names the C++ compiler. For course work, it should point to the compiler configured for the Bellagio environment.

CXXFLAGS contains the course compiler options. These options include the C++ language standard, warning settings, and debugging information. Do not redefine CXXFLAGS in your Makefile unless an assignment specifically tells you to do so.

To see the compiler command configured on Bellagio, run:

echo $CXX

To see the compiler options configured on Bellagio, run:

echo $CXXFLAGS

To show those options one per line, run:

echo $CXXFLAGS | tr ' ' '\n'

A simple Makefile#

This example builds a program named main from one source file:

main: main.cpp
	$(CXX) $(CXXFLAGS) main.cpp -o main

clean:
	rm -f main

The command lines under main: and clean: must begin with a tab character, not spaces. This is one of the most common Makefile mistakes.

Build the program:

make

Remove the executable:

make clean

Multiple source files#

For a small project with multiple source files:

main: main.cpp helper.cpp helper.h
	$(CXX) $(CXXFLAGS) main.cpp helper.cpp -o main

clean:
	rm -f main

These examples use $(CXX) and $(CXXFLAGS) from the Bellagio environment. That keeps your Makefile consistent with the compiler and options used for the course.

Useful make commands#

make
make clean
make main
make -n

make -n prints the commands that would run without actually running them. That is useful when you are checking a Makefile.

Good habits#

  • Keep the Makefile in the same directory as the source files for a small project.
  • Use tabs before recipe commands.
  • Rebuild after changing source files.
  • Run make clean if you suspect stale output.
  • Read the first Makefile error before trying to fix later messages.
Note: The page you are viewing
is not sanctioned by CSN.