Reputation: 169
I have p1.c
p2.c
... pn.c
, a sharedprg.c
and a sharedprg.h
files in a directory, I want to create a make file to compile all these programs, for example something like this
for i in {1..n} // just a pseudo code to tell what's in my mind
gcc -o p$i p$i.c sharedprg.c
And every time I invoke make
it should just re compile pi
if pi.c
changed or-else compile all the programs if either sharedprg.c
or shareprg.h
changed. Is there any way I can achieve this?
Edit: I would get the result which I wanted using this code
shared = sharedMem.c sharedMem.h
all: p1 p2 p3
%.o: %.c
gcc -c $^
p1: p1.o $(shared)
gcc -o p1 p1.o sharedMem.c
p2: p2.o $(shared)
gcc -o p2 p2.o sharedMem.c
p3: p3.o $(shared)
gcc -o p3 p3.o sharedMem.c
clean:
rm -f *.o p1 p2 p3
But please suggest if there is a better or easier way (with out adding $(shared)
everywhere)
Upvotes: 0
Views: 71
Reputation: 5301
If you change the $^
to $<
in the compile rule, you can add the extra header prerequisites separately. You can also add prerequisites to multiple targets at once. Some inspiration:
# default target; build all
all: p1 p2 p3
# Fix compile rule to only compile the source (excluding any header prerequisites)
%.o: %.c
gcc -c $<
# programs depend on their respective .o (Static Pattern Rule)
# https://www.gnu.org/software/make/manual/html_node/Static-Usage.html
p1 p2 p3: %: %.o
# all objects depend on sharedMem.h
p1.o p2.o p3.o: sharedMem.h
# all programs depend on sharedMem.o (which is made from sharedMem.c)
p1 p2 p3: sharedMem.o
The built-in rules do this for you, so you can remove the gcc ...
recipe line. If you're a beginner, easiest stick to them. See https://www.gnu.org/software/make/manual/html_node/Catalogue-of-Rules.html
Upvotes: 1