I have 3 files
hellomain.c
hellofunc.c
helloheader.h
and I am running via the GCC compiler. Usually I would type in:
gcc helloheader.h hellomain.c hellofunc.c -o results
And everything would run.
How could this be converted to a makefile? I know I have to title it makefile
. I know I have to call it by typing in make
in the compiler. But not sure what to actually type in the makefile.
Just about the simplest makefile possible for a project like your would be something like this:
# The name of the source files
SOURCES = hellomain.c hellofunc.c
# The name of the executable
EXE = results
# Flags for compilation (adding warnings are always good)
CFLAGS = -Wall
# Flags for linking (none for the moment)
LDFLAGS =
# Libraries to link with (none for the moment)
LIBS =
# Use the GCC frontend program when linking
LD = gcc
# This creates a list of object files from the source files
OBJECTS = $(SOURCES:%.c=%.o)
# The first target, this will be the default target if none is specified
# This target tells "make" to make the "all" target
default: all
# Having an "all" target is customary, so one could write "make all"
# It depends on the executable program
all: $(EXE)
# This will link the executable from the object files
$(EXE): $(OBJECTS)
$(LD) $(LDFLAGS) $(OBJECTS) -o $(EXE) $(LIBS)
# This is a target that will compiler all needed source files into object files
# We don't need to specify a command or any rules, "make" will handle it automatically
%.o: %.c
# Target to clean up after us
clean:
-rm -f $(EXE) # Remove the executable file
-rm -f $(OBJECTS) # Remove the object files
# Finally we need to tell "make" what source and header file each object file depends on
hellomain.o: hellomain.c helloheader.h
hellofunc.o: hellofunc.c helloheader.h
It could be even simpler, but with this you have some flexibility.
Just for completeness sake, this is probably the most simple makefile possible:
results: hellomain.c hellofunc.c helloheader.h
$(CC) hellomain.c hellofunc.c -o results
This is basically doing what you're already doing on the command-line. It's not very flexible and it will rebuild everything if any file changes.