This Makefile is a fully functional sample for compiling several C sources
(here foo.c
and bar.c
) and link the resulting object files into an
executable program (here foobar
):
SOURCES = foo.c bar.c
PROGRAM = foobar
ifdef CC65_TARGET
CC = $(CC65_HOME)/bin/cl65
CFLAGS = -t $(CC65_TARGET) --create-dep -O
LDFLAGS = -t $(CC65_TARGET) -m $(PROGRAM).map
else
CC = gcc
CFLAGS = -MMD -MP -O
LDFLAGS = -Wl,-Map,$(PROGRAM).map
endif
########################################
ifdef CC65_TARGET
define MAKEDEPEND
sed -e"s!$(<:.c=.s)!$@!p" -e"s![^:]*:.\(.*\)!\1:!" < $(<:.c=.u) > $(@:.o=.d)
$(RM) $(<:.c=.u)
endef
endif
.SUFFIXES:
.PHONY: all clean
all: $(PROGRAM)
ifneq ($(MAKECMDGOALS),clean)
-include $(SOURCES:.c=.d)
endif
%.o: %.c
$(CC) -c $(CFLAGS) -o $@ $<
@$(MAKEDEPEND)
$(PROGRAM): $(SOURCES:.c=.o)
$(CC) $(LDFLAGS) -o $@ $^
clean:
$(RM) $(SOURCES:.c=.o) $(SOURCES:.c=.d) $(PROGRAM) $(PROGRAM).map
Important: When using the sample Makefile above via copy & paste it is necessary to replace the eight spaces at the beginning of command lines (lines 33, 34, 37 and 40) with a tab character (ASCII code 9).
Without any specific configuration the sample Makefile will compile and link
using GCC. In order to rather use cc65 the variable CC65_TARGET
needs to be
defined. This may by done as an environment variable or simply as part of the
Makefile. However to quickly switch between compilers and/or cc65 targets it is
best done on the GNU Make command line like this:
make CC65_TARGET=c64
The sample Makefile doesn't require cc65 to be "installed" in any way. Rather it
only presumes the single variable CC65_HOME
to point to the directory the
cc65 packages were unpacked into. Again there are several ways to define this
variable but as its value typically won't change often it is best done as an
environment variable.
Most parts of the sample Makefile follow the guidelines in the GNU Make Manual that can be searched online for background information. The automatic generation of dependency however rather works as described by the GNU Make maintainer Paul D. Smith in Advanced Auto-Dependencies.
In the meantime GCC supports this method directly with the preprocessor option
-MP
while cc65 requires some post-processing of the dependency file with
sed
adding a second line like in this example:
foo.o: foo.c foo.h bar.h
foo.c foo.h bar.h:
The recommended way to use GNU Make on Windows is to install it as part of a Cygwin environment. For more information see the Cygwin home page:
If however installing Cygwin shouldn't be an option for one or the other reason then the sample Makefile may be invoked from the Windows Command Prompt (cmd.exe) by downloading the following programs: