Linux: A Sample makefile

In Linux, you can write a makefile easily if you use the predefined variables of GNU make and its built-in rules. Consider, for example, a makefile that creates the executable xdraw from three C source files (xdraw.c, xviewobj.c, and shapes.c) and two header files (xdraw.h and shapes.h).

Assume that each source file includes one of the header files. Given these facts, here is what a sample makefile may look like:

This makefile relies on GNU make’s implicit rules. The conversion of .c files to .o files uses the built-in rule. Defining the variable CFLAGS passes the flags to the C compiler.

The target named all is defined as the first target for a reason — if you run GNU make without specifying any targets in the command line, the command builds the first target it finds in the makefile.

By defining the first target all as xdraw, you can ensure that make builds this executable file, even if you don’t explicitly specify it as a target. Unix programmers traditionally use all as the name of the first target, but the target’s name is immaterial; what matters is that it’s the first target in the makefile.