.Dd September 17, 2018
.Dt MAKE 7
.Os "Causal Agency"
.
.Sh NAME
.Nm Using Make
.Nd writing less Makefile
.
.Sh DESCRIPTION
Let's talk about
.Xr make 1 .
I think an important thing to know about
.Xr make 1
is that you don't need to write a
.Pa Makefile
to use it.
There are default rules
for C, C++ and probably Fortran.
To build
.Pa foo
from
.Pa foo.c ,
just run:
.
.Pp
.Dl make foo
.
.Pp
The default rule for C files uses the
.Ev CFLAGS
variable,
so you can set that in the environment
to pass flags to the C compiler:
.
.Pp
.Dl CFLAGS=-Wall make foo
.
.Pp
It also uses
.Ev LDLIBS
for linking,
so you can add libraries with:
.
.Pp
.Dl LDLIBS=-lcurses make foo
.
.Pp
Obviously writing this every time
would become tedious,
so it might be time to write a
.Pa Makefile .
But it really doesn't need much:
.
.Bd -literal -offset indent
CFLAGS += -Wall -Wextra
LDLIBS = -lcurses

foo:
.Ed
.
.Pp
Assigning
.Ev CFLAGS
with
.Ql +=
preserves the system default
or anything passed in the environment.
Declaring
.Pa foo
as the first rule
makes it the default when
.Ql make
is run without a target.
Note that the rule doesn't need a definition;
the default will still be used.
.
.Pp
If
.Pa foo
is built from serveral source files,
unfortunately a rule definition is required:
.
.Bd -literal -offset indent
OBJS = foo.o bar.o baz.o

foo: $(OBJS)
	$(CC) $(LDFLAGS) $(OBJS) $(LDLIBS) -o $@
.Ed
.
.Pp
This rule uses
.Ev LDFLAGS
for passing linker flags,
which is what the default rule does.
The
.Ql $@
variable here expands to
.Ql foo ,
so this rule can be copied easily
for other binary targets.
.
.Pp
If some sources depend on a header file,
they can be automatically rebuilt
when the header changes
by declaring a dependency rule:
.
.Pp
.Dl foo.o bar.o: foo.h
.
.Pp
Note that several files can appear
either side of the
.Ql ":" .
.
.Pp
Lastly,
it's always nice to add a
.Cm clean
target:
.
.Bd -literal -offset indent
clean:
	rm -f $(OBJS) foo
.Ed
.
.Pp
I hope this helps getting started with
.Xr make 1
without writing too much
.Pa Makefile !
.
.Sh EXAMPLES
The example
.Pa Makefile
in its entirety:
.
.Bd -literal -offset indent
CFLAGS += -Wall -Wextra
LDLIBS = -lcurses
OBJS = foo.o bar.o baz.o

foo: $(OBJS)
	$(CC) $(LDFLAGS) $(OBJS) $(LDLIBS) -o $@

foo.o bar.o: foo.h

clean:
	rm -f $(OBJS) foo
.Ed
.
.Sh AUTHORS
.An Mt june@causal.agency
.
.Pp
This document is produced from
.Xr mdoc 7
source available from
.Lk https://git.causal.agency/src/tree/www/text.causal.agency