Make and Makefiles

by Anu Rao

Why Use make and makefiles?

Running make

To run make, at the Linux prompt simply type


By default it looks for a makefile with the name makefile or Makefile, otherwise you can specify the alternate name of your makefile with

make -f altfilename

Sample Makefiles

Let's say we have 3 pieces of C code: our main program main.c with two subroutines contained in sub1.c and sub2.c, that use the library /usr/lib/mylib.a. Then a simple, bare-bones, nothing-too-fancy makefile for this code would look like:

progex: main.o sub1.o sub2.o /usr/lib/mylib.a
        cc -o progex main.o sub1.o sub2.o /usr/lib/mylib.a
  |____important: TAB necessary

main.o: main.c
        cc -c main.c
sub1.o: sub1.c
        cc -c sub1.c
sub2.o: sub2.c
        cc -c sub2.c

where progex is the name of the executable for our code. Note that every command has to begin with a TAB.

Here is another generic Makefile with a some simple options, for C or FORTRAN code.


Macros allow one to store commands or long names in variable names. Macros are defined (in capital letters) in makefiles by

MACRONAME= text string and referenced within a makefile by $(MACRONAME). Note that you will never get an error message for an undefined macro.

There are built-in macros, such as CC, LD, FC, F77. To view the default built-ins, type

make -p or make -fp - < /dev/null  
Generally options to cc are stored in CFLAGS, options to f77 are stored in FFLAGS, etc.

One can also use macros for string substitution. Here is as example: define SRCS = main.c defs.c redraw.c close.c. Then $(SRCS:.c.o) is a macro for main.o defs.o redraw.o close.o.

Suffix Rules

If a *.o file is specified, then suffix rules dictate that it could have come from *.f, *.c. So, using macros and suffix rules we can rewrite our simple, bare-bones, nothing-too fancy makefile for main.c, sub1.c, sub2.c (from above) as:

OBJS = main.o sub1.o sub2.o
LIB = /usr/lib/mylib.a
progex: $(OBJS) $(LIB)
        cc -o progex $(OBJS) $(LIB)

Status and Debugging

make -n
runs through the motions without actually executing any commands
make -s
executes all the commands but does not echo them
make -d
debug mode

Helpful Hints/Notes for make
Last modified: Tue, 06 Aug 2013 11:52:55 -0600
Valid XHTML 1.0! Valid CSS!