Lil' Bits
Lil' Bits

Reputation: 898

Clean directive not working in makefile

I am writing a makefile for my program "p1", but I can't get my "clean" to work.

#Default target
p1: main.o bst_insert.o bst_info.o
    gcc main.o bst_insert.o bst_info.o -o p1

#START Dependencies for default target
main.o: const.h bst_insert.h bst_info.h bst_struct_def.h main.c
    gcc -c main.c

bst_insert.o: bst_struct_def.h bst_insert.h bst_insert.c
    gcc -c bst_insert.c

bst_info.o: bst_struct_def.h bst_info.h bst_info.c
    gcc -c bst_info.c
#END Dependencies for default target

#Target for removing unnecessary files.
clean:
    rm -f *.o core

Here is the before/after:

make_before_after

For whatever reason, "clean" never executes. Can someone tell me why? I'm new to makefiles so I could be making a very obvious mistake that I'm not aware of.

Upvotes: 0

Views: 388

Answers (2)

MadScientist
MadScientist

Reputation: 101131

If you don't give it a specific target to build on the command line, then make will always build the first target in the makefile. It will ensure that target is up to date by checking all its prerequisites, and their prerequisites, etc. and ensuring they're up to date, then building the target (if needed).

Any targets which are not part of that tree will not be built unless you specifically request it. So in this example, clean is not the first target, and it's not a prerequisite of the first target, etc. so it's not built. If you want it built you should run make clean to request that it be built, or you need to add it into the prerequisite list. However, doing that is tricky because you want it run last. So you'd need to do something like this:

clean: p1
        rm -f *.o

as the first target. Now clean will be run, but before that can happen p1 will be built, etc.

However, this is very unusual and unlikely to be what you want. The entire point of having a makefile is so that you only have to recompile the files that have changed and not recompile the files you haven't changed. If you delete all the object files every time, then every time you run make it will have to recompile everything.

If you always want everything recompiled every time, then make is useless. You might as well just write a shell script that will compile your code then delete all the objects.

Upvotes: 3

akond
akond

Reputation: 16060

You should run it manually: make p1 clean

Besides, your Make file could have been much shorter.

p1: bst_info.o bst_insert.o bst_struct_def.o
        gcc $^ -o $@

clean:
        rm -f *.o

Upvotes: 2

Related Questions