GNU make

Tags
    :cheatsheet:
url
https://bytes.usc.edu/cs104/wiki/makefile/

Simple Example

This simple Makefile compiles a hello.cpp program. It also includes a clean target that removes our executable in case we want to clean up the directory.

   hello: hello.cpp
	g++ -g -Wall hello.cpp -o hello

clean:
	rm -f hello

Multi-file Example

It’s important to note a target can be named after after a file. This is most commonly used to:

Indicate that our target requires a file that must be compiled by another target. Only run our target when that dependency has changed to avoid doing extra work.

Most of your homeworks will require you to compile multiple files, then link them all at once. To do this, we’ll use the -c compiler flag, which compiles without linking. Note that all the files we compile with -c have target names that correspond to the object files we’re expecting out.

First, take a look at the imaginary file tree we’re basing this Makefile off of:

program/ main.cpp file1.cpp file1.h file2.cpp
all: program

program: main.cpp file1.o file2.o
	g++ -g -Wall main.cpp file1.o file2.o -o program

file1.o: file1.cpp file1.h
	g++ -g -Wall -c file1.cpp -o file1.o

file2.o: file2.cpp
	g++ -g -Wall -c file2.cpp -o file2.o

clean:
	rm -f *.o program

When you type make or make [target], the Make will look through your current directory for a Makefile. This file must be called makefile or Makefile. Make will then look for the corresponding target in the makefile. If you don’t provide a target, Make will just run the first target it finds. If the target is found, the target’s dependencies will be run as needed, then the target commands will be run. Oftentimes these commands start with g++, but they can be anything! You can run any command this way.

The target dependency format looks like this. Note the tab indent before the commands; these are required!

target1: dependency1 dependency2 ...
	command1
	command2
	...