2

I was trying to come up with a solution for automatic dependency using gcc/g++/nvcc and a Makefile.

I thought I'd come up with a solution, to call gcc -M $(SRC FILES) in a Makefile before any compilation targets, with the assumption that Make would now have updated rules for the compilation targets.

An example of the Makefile I've thought would work is as follows:

PROG = main.out

SRC = $(wildcard *.cc)
OBJ = $(SRC:.cc=.o)

all: $(PROG) | deps

$(PROG): $(OBJ)
    g++ -o $@ $^

$(OBJ): $(SRC)
    g++ -c $<

.PHONY: deps

deps:
    g++ -M $(SRC)

Now I'm wondering if the call to

    g++ -M $(SRC)

Just causes the dependencies to be printed to stdout and infact the Makefile is still none the wiser to the automatic dependencies.

Ideally I'm looking for a solution that will run in a single pass of a Makefile and use gcc/g++/nvcc automatic dependency flags, and preferably one that doesn't require saving the dependencies to a whole bunch of files.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Sam Jones
  • 77
  • 7

1 Answers1

3

You can do something like below to get both .o and .d files:

g++ -c main.cpp -o main.o -MP -MMD -MF main.d

So define your dependency files (e.g. DEPFILES) in your Makefile and generate .d like the above command, then include DEPFILES by -, which tells GNU Make to include the dep file if it exists.

-include $(DEPFILES)
Mine
  • 4,123
  • 1
  • 25
  • 46
  • The simplest solution I found that is generic enough for my uses is here: http://stackoverflow.com/a/21086223/5791272 It is quite similar to your approach but doesnt use both '-MMD' and '-MF'. – Sam Jones Sep 25 '16 at 00:22