Reputation: 516
I'm using makefile with gcc. Every c file has an accompanying header:
main.c main.h
test.c test.h
main.c includes main.h and test.h
test.c includes test.h
I want to avoid recompiling every c file. Makefile is ran without -B argument.
I can write the whole makefile manually and specify every dependency. When editing headers only the necessary c files get recompiled. An edit in test.h will recompile both c files and a change in main.h will only recompile main.c. As it should.
This doesn't work when I switch to the more automated approach:
OBJ = main.o test.o
%.o: %.c %.h
$(CC) -c -o $@ $<
main: $(OBJ)
$(CC) -o main $(OBJ)
A change in test.h will only recompile test.c. Leaving main.c in the old with the old version of test.h header. I'm forced to run makefile with -B, if I want to use this approach.
I can specify the headers manually:
DEPS = main.h sort.h
%.o: %.c $(DEPS)
$(CC) -c -o $@ $<
Then a change in main.h recompiles both main.c and test.c, the latter being unnecessary.
Updating every change in the makefile is unwieldy if I have a lot of files, and using the automated approach will increase compilation times.
Is there a better solution, one that only recompiles the needed files, or is specifying everything manually the only way?
Upvotes: 0
Views: 782
Reputation: 100856
If you decide to specify manually, though, you're doing it wrong; you don't want to add the dependencies to the pattern where it takes effect for every object file. You define it separately for each object file so they're only rebuilt when the right ones change:
OBJ = main.o test.o
%.o: %.c
$(CC) -c -o $@ $<
main: $(OBJ)
$(CC) -o main $(OBJ)
main.o: main.h test.h
test.o: test.h
Maintaining those last lines is what the automated dependency generation does, if you decide you want to try to use it.
Upvotes: 0
Reputation: 206607
You can specify additional dependencies of main.o
using another line:
OBJ = main.o test.o
main.o: test.h
Upvotes: 1