Reputation: 14781
Say, I have several source codes, a.c, b.c, ..., z.c
, and I want a rule to have each of them compiled. Here is a solution:
%.o: %.c
$(CC) -c -o $@ $(CFLAGS) $<
Then I introduce a header c.h
used in c.c
, and another header e.h
used in c.c
and e.c
, and things become complex:
%.o: %.c
$(CC) -c -o $@ $(CFLAGS) $<
c.o: c.c c.h e.h
$(CC) -c -o $@ $(CFLAGS) $<
e.o: e.c e.h
$(CC) -c -o $@ $(CFLAGS) $<
Based on the solution of condition 1, is there something like add_dependency
in make
to simplify the solution and obtain something like the following one?
%.o: %.c
$(CC) -c -o $@ $(CFLAGS) $<
add_dependency(c.o, c.h e.h)
add_dependency(e.o, e.h)
Or, what do you think is a better solution to condition 1?
EDITED:
Thanks for the kind notice @ctheo :)
Yes I did have a look at autotools
and understood that shall satisfy all my needs. However what I'm dealing with is an existing project and its Makefile
contains other directives dealing with codes in C++
, and I think for now I'd better just modify a few lines instead of port the whole Makefile
to autotools
, unless I couldn't find a satisfying solution without introducing autotools
. :)
Upvotes: 18
Views: 11395
Reputation: 117
In addition, the .o
files in your example all depend on a .h
file with the same stem, so you can generalise that part of your rules too:
c.o: e.h
%.o: %.c %.h
$(CC) -c -o $@ $(CFLAGS) $<
This way, your “normal” situations are covered entirely by the rule that triggers compilation and your “unusual” situations stand out because those are the only additional rules.
Upvotes: 3
Reputation: 3612
At first I did not expected to exist a solution for this. It seemed to me that it was covered by autotools
. However, after some search, I found this section of GNU/make manual.
It states that :
One file can be the target of several rules. All the prerequisites mentioned in all the rules are merged into one list of prerequisites for the target.
So there is a solution for your query
c.o: c.h e.h
e.o: e.h
%.o: %.c
$(CC) -c -o $@ $(CFLAGS) $<
Thanks for insisting. I learned something today :)
Upvotes: 18