Search code examples
makefilegnu-make

GNU make: how prevent '-include file.ext' from executing a rule the target of which is 'file.ext'?


Just to review the terminology, this is the structure of a makefile 'rule':

target:   dependencies ...
          commands
          ...

This is the makefile I've written:

CC = mpicc
SHAREDLIB = libfmd.so
CFLAGS = -fPIC -Wall -Wno-unused-result -O3 -fopenmp
LFLAGS = -lm -fopenmp -lgsl -lgslcblas

OBJS = $(patsubst %.c,%.o,$(wildcard *.c))

.PHONY: all shared clean
all: shared
shared: $(SHAREDLIB)
$(SHAREDLIB): depend.mk $(OBJS)
    $(CC) $(OBJS) -shared -o $@ $(LFLAGS)
depend.mk: *.c *.h
    $(CC) -MM *.c > depend.mk
-include depend.mk
clean:
    rm -f *.o libfmd.so depend.mk

When the folder is clean, and I enter make clean, the following lines are shown:

mpicc -MM *.c > depend.mk
rm -f *.o libfmd.so depend.mk

It seems to me that -include depend.mk in addition to including depend.mk, executes the rule that depend.mk is its target. I'd like to stop this behavior.


Solution

  • You are correct. See How Makefiles are Remade in the documentation.

    There is no way to prevent this behavior: if there's a rule that creates an included makefile, make will always rebuild it if it's out of date, then re-invoke itself to read the latest version.

    The question is, why do you want to avoid it? Maybe if you explained the behavior you are actually looking for at a higher level we could help. As you have it here it's possible for .o files to be created without any depend.mk file created, then a compile fails, you modify a header file to fix it, but since the depend.mk file doesn't exist when you re-run make the source files are not rebuilt properly.

    If you want to get accurate handling of C/C++ dependencies with GCC you might take a look at Auto-Dependency Generation.