My golden Makefile for compiling single-file C programs

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

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)

clean:
      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.

Add a Comment

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