My golden Makefiles for compiling C programs

This post was written by eli on August 11, 2016
Posted Under: Linux,Software

Single-source utilities

This is the Makefile I use for compiling a lot of simple utility programs, one .c file per utility:

CC=    gcc
FLAGS=  -Wall -O3 -g

ALL=    broadclient broadserver multicastclient multicastserver
all:    $(ALL)

      rm -f $(ALL)
      rm -f `find . -name "*~"`

%:    %.c Makefile
      $(CC) $< -o $@ $(FLAGS)

The ALL variable contains the list of output files, each have a corresponding *.c file. Just an example above.

The last implicit rule (%: %.c) tells Make how to create an extension-less executable file from a *.c file. It’s almost redundant, since Make attempts to compile the corresponding C file anyhow, if it sees a target file with no extension (try “make –debug=v”). If the rule is removed, and the CFLAGS variable is set to the current value of FLAGS, it will work the same, except that the Makefile itself won’t be dependent on.

IMPORTANT: Put the dynamic library flags (e.g. -lm, not shown in the example above) last in the command line, or “undefined reference” errors may occur on some compilation platforms (Debian in particular). See my other post.

Multiple-source utilites

CC=    gcc
ALL=    util1 util2
OBJECTS = common.o
HEADERFILES = common.h
FLAGS=    -Wall -O3 -g

all:    $(ALL)

 rm -f *.o $(ALL)
 rm -f `find . -name "*~"`

%.o:    %.c $(HEADERFILES)
 $(CC) -c $(FLAGS) -o $@ $<

$(ALL) : %: %.o Makefile $(OBJECTS)
 $(CC) $< $(OBJECTS) -o $@ $(LIBFLAGS)

Note that in this case LIBFLAGS is used only for linking the final executables

Add a Comment

required, use real name
required, will not be published
optional, your blog address