How to use a makefile

Jan 29, 2017 at 12:16am
I've written a makefile and saved it under the name "MakeFile" (provided below) for my program. It's in the same folder as my programs. I'm using a Macbook pro and sublime text 3 for my text editor. I'm also using my computer's terminal to compile my code.

all: main

main.o: main.cc Greetings.cc
g++ -c -Werror main.cc

Greetings.o: Greetings.cc Greetings.h
g++ -c -Werror Greetings.cc

main: main.o Greetings.o
g++ -0 main main.o Greetings.o



Now how do I actually use the makefile? I read that you should type in make [options] [target1 target2 ...]. What are options and target? As an experiment, I tried typing "make MakeFile" and I got an error as shown below.

Conrados-MBP:~ conrados$ make MakeFile
make: *** No rule to make target `MakeFile'. Stop.
Last edited on Jan 29, 2017 at 4:42am
Jan 29, 2017 at 9:05am
If you want to specify which makefile to use you can do so using the -f option.

make -f MakeFile

If you rename the file as makefile or Makefile it should be able to find it automatically.

make

If you don't specify a target it will automatically choose the default target which is the first target in the makefile. By convention it should build the whole program and be named all, exactly as you have it.

You also have three other targets main.o, Greetings.o and main.
The main.o target is the recipe for how to create the file main.o.
The Greetings.o target is the recipe for how to create the file Greetings.o.
The main target is the recipe for how to build the main file (the executable).

You can specify which target you want and it will only run the code for that target (and all prerequisite targets).

make Greetings.o

This will only execute ´g++ -c -Werror Greetings.cc´ but only if necessary. If Greetings.o already exist, and the files Greetings.cc and Greetings.h has not been modified since Greetings.o was last created, it will not run the compiler command.
Last edited on Jan 29, 2017 at 9:29am
Topic archived. No new replies allowed.