A Simple Makefile Tutorial
A Simple Makefile Tutorial
A Simple Example
#include <hellomake.h>
#include <hellomake.h>
/*
int main() {
void myPrintHelloMake(void) {
example include file
*/
myPrintHelloMake();
printf("Hello makefiles!\n");
void myPrintHelloMake(void);
return(0);
return;
Normally, you would compile this collection of code by executing the following command:
This compiles the two .c files and names the executable hellomake. The
-I. is included so that gcc will look
in the current
directory (.) for the include file hellomake.h. Without a makefile,
the typical approach to the
test/modify/debug cycle is to use the up
arrow in a terminal to go back to your last compile command so you
don't have to type it each time, especially once you've added a few
more .c files to the mix.
The simplest makefile you could create would look something like:
Makefile 1
hellomake: hellomake.c hellofunc.c
gcc -o hellomake hellomake.c hellofunc.c -I.
One very important thing to note is that there is a tab before the gcc
command in the makefile. There must be
a tab at the beginning of any
command, and make will not be happy if it's not there.
Makefile 2
https://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/ 1/3
1/11/22, 1:10 PM A Simple Makefile Tutorial
CC=gcc
CFLAGS=-I.
Makefile 3
CC=gcc
CFLAGS=-I.
DEPS = hellomake.h
This addition first creates the macro DEPS, which is the set of .h
files on which the .c files depend. Then we
define a rule that applies
to all files ending in the .o suffix. The rule says that the .o file
depends upon the .c
version of the file and the .h files included in
the DEPS macro. The rule then says that to generate the .o file,
make needs to compile the .c file using the compiler defined
in the CC macro. The -c flag says to generate the
object file, the
-o $@ says to put the output of the compilation in the file
named on the left side of the :, the
$< is the first item in
the dependencies list, and the CFLAGS macro is defined as above.
Makefile 4
CC=gcc
CFLAGS=-I.
DEPS = hellomake.h
hellomake: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS)
https://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/ 2/3
1/11/22, 1:10 PM A Simple Makefile Tutorial
Makefile 5
IDIR =../include
CC=gcc
CFLAGS=-I$(IDIR)
ODIR=obj
LDIR =../lib
LIBS=-lm
_DEPS = hellomake.h
hellomake: $(OBJ)
.PHONY: clean
clean:
So now you have a perfectly good makefile that you can modify to
manage small and medium-sized software
projects. You can add multiple
rules to a makefile; you can even create rules that call other
rules. For more
information on makefiles and the make
function, check out the GNU Make Manual, which will tell you more
than you ever wanted to know (really).
https://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/ 3/3