Fabio
Fabio

Reputation: 2277

makefile target dependencies dependent on target name

I have the following rule:

SPECIAL = file1 file2

%.o : %.cpp a.h
    $(CC) -c $(CFLAGS) $< -o $@

I would like that if % is in $(SPECIAL), then b.h is added to the list of dependencies.

Is there a way to do it, without repeating the rule?

Upvotes: 2

Views: 2410

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136208

You can assign additional dependencies separately. Just add a line at the end:

$(addsuffix .o,${SPECIAL}): b.h

To not have to deal with dependency order, replace $< in the rule with $(filter %.cpp,$^). This way %.cpp does not have to be the first dependency.


Ideally, you want the header dependencies to be generated automatically to avoid specifying them manually.

The most simple automatic dependency generation:

%.o : %.cpp 
    $(CXX) -c -o $@ -MD -MP $(CXXFLAGS) $(filter %.cpp,$^)

ifneq ($(MAKECMDGOALS),clean)
-include $(wildcard *.d)
endif   

Upvotes: 4

Related Questions