GNU make
CREATED: [2022-02-10 Thu 22:21] ID: 2fd6389f-5d80-4b4a-9e7a-75e9928a2c01 ROAM_REFS: https://www.gnu.org/software/make/manual/make.html https://bytes.usc.edu/cs104/wiki/makefile/ REVIEW_SCORE: 0.0 MTIME: [2024-12-25 Wed 15:54]
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 ...
This node is a singleton!