HomeModulesModule 2.1 (Makefiles) Extend
I ntroduce
C onnect
A pply
R eflect
E xtend

Extend - Makefiles

If you need to compile multiple C or C++ programs you can make use of special Makefile targets. This can significantly reduce the length of your Makefile and improve maintainability. For example, consider the following Makefile:


CC = /usr/bin/gcc
CFLAGS = -W -O
LIBS = -lm

server: server.o create_socket.o
$(CC) server.o create_socket.o -o server $(LIBS)

client: client.o make_connection.o
$(CC) client.o make_connection.o -o client $(LIBS)

.c.o:
$(CC) $(CFLAGS) -c $<

clean:
rm client server *.o


You may recognize this Makefile from the Apply section. It has been rewritten using both special Makefile targets and macros. When `make server` is invoked, `make` checks the dependencies for the 'server' target, server.o and create_socket.o. Since there is no explicit rule to make either object file, `make` uses the special '.c.o' target, which creates an object file (.o) from C source code (.c). The rule for the '.c.o' target uses the special Makefile macro, $@. The meaning of this and other useful macros can be found in the table below:

$@
Full name of the current target
$<
The source file of the current dependency
$^
The list of all dependencies for the target
$?
The list of dependencies that are newer than the target

You'll also note the lack of $(CFLAGS) in either the 'server' or 'client' targets. Once the compiler has created object files, it no longer needs to compile anything and thus has no need for $(CFLAGS).

Try rewriting one of your Makefiles using macros. Can you think of instances where using macros would be beneficial? Can you think of instances where using macros would be detrimental?

Click here to move on to the next Module (C-Coding - Args).