Makefile g++ -o flag causing redundant compilation

Hi all,

I'm relatively new to Makefiles, and while I can usually get them to work, I am a little confused about how make determines what files need to be recompiled.

Consider the following Makefile:

1
2
3
4
5
6
7
8
9
10
CC=g++

all: hi.o
	$(CC) -o hi hi.o

hi.o: hi.c hi.h
	$(CC) -c hi.c
	
clean:
	rm -f hi.o hi


This works exactly as I expect it to: if I invoke "make" it compiles hi.c into hi.o, links hi.o and produces the hi executable, and if I call "make" again, hi.c is NOT recompiled because make can tell it hasn't been altered since hi.o was created.

However, suppose I want to keep my top level folder less cluttered, so I create a folder to store the (not yet linked) object files? Then I have to alter the above Makefile somewhat:

1
2
3
4
5
6
7
8
9
10
CC=g++

all: hi.o
	$(CC) -o hi obj/hi.o

hi.o: hi.c hi.h
	$(CC) -c hi.c -o obj/hi.o
	
clean:
	rm -f obj/hi.o hi


This works just fine. However, if I invoke "make" a second time, without changing the source code hi.c or hi.h, hi.c is still recompiled. Does anyone see what about the second Makefile is causing this redundancy to occur?

Thanks in advance for any help/suggestions.
-Ben
Last edited on
I think you have your dependencies wrong. You are depending on hi.o for all rather than the linked executable hi. So when you moved your object file into obj/ you are still depending all: upon the now missing hi.o (because it moved).

It would be better to make all: depend on the final executable:

1
2
3
4
5
6
7
8
9
10
CC=g++

all: hi
	$(CC) -o hi obj/hi.o

obj/hi.o: hi.c hi.h
	$(CC) -c hi.c -o obj/hi.o
	
clean:
	rm -f obj/hi.o hi
Last edited on
Sorry, its a while since I made a Makefile:


CC=g++

all: hi

hi: obj/hi.o
	$(CC) -o hi obj/hi.o
	
obj/hi.o: hi.c hi.h
	$(CC) -o obj/hi.o -c hi.c
	
clean:
	rm -f hi obj/*.o 
I see: I was missing something fundamental (I guess it should have been obvious), which is that make targets are assumed to refer to actual files. I've gotten used to Ant, where the "targets" are just names for performing a bunch of tasks. Thank you so much, that helps me tremendously.
Topic archived. No new replies allowed.