Skip to main content

15.6) Example of a Makefile


prog: file1.o file2.o file3.o
        g++ file1.o file2.o file3.o -o prog
file1.o: file1.cpp file1.hpp
        g++ -c file1.cpp
file2.o: file2.cpp file2.hpp
        g++ -c file2.cpp
file3.o: file3.cpp file3.hpp
        g++ -c file3.cpp
clean:
        rm -f file1.o file2.o file3.o
veryclean: clean
        rm -f prog

  • Rules start with a target (the thing we are trying to build), then a colon, then a space-separated list of dependencies (the things from which the target is built)
  • Commands to execute appear on lines underneath
  • Each command MUST begin with a single tab character (NOT spaces!)
  • Rules don't have to be compiler-related; the clean and veryclean targets in the example above are used for clean-up operations, removing the object code files in the case of clean or the object code and executable in the case of veryclean
  • Make will display each command that it executes, unless that command begins with the @ symbol