Makefile basics

I'm having trouble with the basics of the makefile.

I am using gcc to compile

I need to make a makefile named labMakefile and the targets



the files already in the folder I'm working in consist of



I have looked at tutorials on makefiles but I cannot find a suitable way to create a makefile

What i tried

labMakefile: labM.o labG.o


but he just says labMakefile:: command not found


source to share

2 answers

The make file is the script that Make runs. It is just a text file, written with a strict grammar that does needs like source code (although it is interpreted, not compiled). You can use any text editor you like to create.

You are using C (judging by the suffixes on your filenames). Thus, to create labM.o

from labM.c

, you would probably use a command like

gcc -c labM.c -o labM.o


(Not -o labM.o

really needed, this is the default behavior, I'm just trying to explain something.) Also, to build labG.o

, you have to use

gcc -c labG.c -o labG.o


and then (I think) you would link them together to create a lab:

gcc labM.o labG.o -o lab


And sometimes you want to clean up the built files:

rm -f *.o lab


To do all this, write a makefile titled Makefile

that looks like this (note that leading spaces are TAB):

    gcc -c labM.c -o labM.o

    gcc -c labG.c -o labG.o

    gcc labM.o labG.o -o lab

    rm -f *.o lab


Then you could make lab

either make clean

or make labM.o labG.o

. If you really want to call this makefile labMakefile

, you can do it, but then you have to do it for example. make -f labMakefile lab

... This makefile is crude but efficient. It could be significantly improved:

CC = gcc

lab: labM.o labG.o
    gcc $^ -o $@

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

    @echo cleaning things up, boss...
    @rm -f *.o lab


It handles dependencies better: if you change labM.c

, but not labG.c

, and then make

, Make will know that labM.o

(s lab

) needs to be rebuilt but labG.o

doesn't need to be.

That's a lot, and there is room for improvement (dependency handling can be very smooth), but it's a good start.



To run the makefile, you must call "make"

If your makefile does not have a standard name (makefile or Makefile), you must specify it with the -f argument:

make -f labMakefile




All Articles