views:

101

answers:

2

I have a directory with 50 .c source files and each one of these .c files depends on a .h file with the same name plus a common header file.

Example:

foo.c depends on foo.h and common.h
bar.c depends on bar.h and common.h
baz.c depends on baz.h and common.h

Is it possible to setup this dependency without having to make a separate target for each .c file?

In case it matters, the ultimate output of this Makefile will be a libfoo.a library containing each of these .o files.

Edit

If at all possible I would like to do this with gnu make syntax and not have a target for each file whether or not that target was created manually or by something like makedepend.

+5  A: 

As far as I know this should suffice.

%.o: %.c %.h common.h
\tgcc -c $<

\t is a tab, and the gcc -c $< is of course just an example.

houbysoft
That did the trick, thanks!
SiegeX
+3  A: 
OBJECTS = $(patsubst %.c,%.o,$(wildcard *.c))
%.o: %.c %.h common.h
    gcc -c $< -o $@

libfoo.a: $(OBJECTS)
    ar rcs $@ $^
bta
Just a tad too late. This is pretty much exactly what I'm doing except I use `$(AR) $(ARFLAGS) $@ $?` and I don't specify the `-o $@` part in the `gcc` line. +1 for the help.
SiegeX
Btw, I like the idea of nesting `$(wildcard)` in the pattern sub without the need for a `SOURCES` variable but I can't get it to work. Maybe you need `$(patsubst)` for this?
SiegeX
Yep, this works --> `OBJECTS = $(patsubst %.c,%.o,$(wildcard *.c))`
SiegeX
You are correct. It seems that the substitution reference and the `patsubst` form are only equivalent when you are transforming text stored in a variable, not when using a nested command. Editing my answer to fix the mistake.
bta