GNU make has a very substantial online manual, and while IMO it is aggravating and obtuse at many points, it does make a decent reference. As others have said, just look around for a tutorial that works for you, and consult the manual along with that so you get used how it is organized, etc.
A basic (GNU make) makefile for building
hello.c might look like:
CFLAGS += -Wall -g -O0
PROGS = hello
$(CC) $(CFLAGS) $< -o $@
$(CC) is a built-in variable; if you don't redefine it, the default is
cc, which on a GNU system will be a symlink to
% indicates a pattern rule; in this case it will match anything, although if there is no
anything.c in the directory the recipe will fail.
$@ are automatic variables. So if you now run:
Make will execute:
cc -Wall -g -O0 hello.c -o hello
+= with `$(CFLAGS) allows you to do stuff like this:
CFLAGS="--std=c99" make hello
-Wall -g -O0 will be appended to
--std=c99, separated by a space. Note that if you use
make CFLAGS="--std=c99" hello, that value will replace any definition in the makefile.
Rules have three basic parts, the targets, the prerequisites, and the recipe (see here). The rule will run if:
- The target file does not exist.
- The target file is older than one of the prerequisites.
.PHONY targets will run no matter what. So running
make clean with the above make file will execute:
In this case
$(PROGS) is not used anywhere else, although in a more complex project make file it might be used as a prerequisite for something else. E.g., if you add this rule to the top (after the variable declarations):
all to the
.PHONY: list, you can now just enter
make and everything in the
$(PROGS) list will be built using the
%: %.c rule, since this is a prerequisite to make
all is the first rule in the file -- used by default if you don't specify one (i.e., you can still use
make hello to build just the "hello" program).