A very brief introduction to Makefiles

The command "make" can be really helpful: instead of giving a whole sequence of compiler commands, worrying about which bits of your program need to be recompiled, you can give a single "make" command and the parts that need recompiling will automatically be identified and recompiled for you.

Even for a short program "make" can be helpful. Suppose you have a program in the file "hello.c". You can compile it with

	gcc hello.c
to give a translated program with the unhelpful name "a.out".

Or you can create a file "makefile" with these contents:

hello: hello.c
	gcc -o hello hello.c
Note that there is a tab before the "gcc" command, above. If you use spaces instead of the tab, it won't work.

Then when you want to compile your program, give the command

	make hello
This is shorter than "gcc hello.c", and it gives the translation a better name, too. In fact, if "hello" is the only program managed by the makefile, you can just give the command
	make

For a program written in more than one source file, "make" really comes into its own. Look in the example "sepcomp" to see this makefile:

pgm: prog.o sub.o
	gcc -o pgm prog.o sub.o
prog.o: incl.h prog.c
	gcc -c prog.c
sub.o: incl.h sub.c
	gcc -c sub.c
The first line tells "make" that pgm depends on prog.o and sub.o. In other words, pgm is out of date if it is older than prog.o or sub.o. If pgm is out of date, then it can be brought up to date with the command
	make
(all by itself, without arguments).

Similarly, prog.o depends on incl.h and prog.c, and can be brought up to date with the command

	make prog.o
If we are "make"ing pgm, possibly both prog.o and sub.o will be out of date; in that case, "make" will issue all the necessary commands:
	gcc -c prog.c
	gcc -c sub.c
	gcc -o pgm prog.o sub.o
"Make" also helpfully tells you when it finds that it does NOT need to recompile something.

A word of caution: Makefiles can become really complicated. Read about the possibilities in the manual page if you like; but don't spend a great deal of time on it. Simple makefiles will do almost everything you want without requiring you to learn a great deal more than I've told you here.