0

I have this makefile

appname := fun

srcfiles := $(shell find .. -name "*.cpp")
headerfiles := $(shell find .. -name "*.hpp")
objects  := $(patsubst %.cpp, %.o, $(srcfiles))


all: $(srcfiles) $(appname)

$(appname): $(objects)
    $(CXX) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)

depend: .depend

.depend: $(srcfiles) $(headerfiles)
    rm -f ./.depend
    $(CXX) $(CXXFLAGS) -MM $^>>./.depend;

clean:
    rm -f $(appname) $(objects)

dist-clean: clean
    rm -f *~ .depend

include .depend

Where the makefile's parent directory contain all the code (.hpp and .cpp files). Unfortunately, the .o files are saved in the source code, while I want that they're saved in the same directory of the executable (and makefile). This is the same of Default in Eclipse CDT.

How can I modify makefile in order to do that?

PS: I found similar questions, like this one, but none of them used depend for defining the $(objects) task (they're all in `%.o% form).

Community
  • 1
  • 1
justHelloWorld
  • 6,478
  • 8
  • 58
  • 138

1 Answers1

1

When you set your objects variable you are simply taking the full pathname to the .cpp file and replacing the suffix with .o. So if you have a file like my/sub/dir/foo.cpp then objects will contain the path my/sub/dir/foo.o. So, of course when you write a rule $(appname): $(objects), make is going to try to build the file my/sub/dir/foo.o. If you want it to build just foo.o instead, then you have to strip off the path as well, not just replace the suffix:

objects := $(patsubst %.cpp,%.o,$(notdir $(srcfiles)))

Now, of course, make will say it doesn't know how to build foo.o, because the default rules only know how to build a .o from a .cpp, not from a .cpp file stashed in my/sub/dir.

To make this work the simplest solution is to use VPATH and you can construct the value for VPATH from the list of directories you got from srcfiles, like so:

VPATH := $(sort $(dir $(srcfiles)))

You might also consider using a better dependency generation solution, for example the one described here.

MadScientist
  • 92,819
  • 9
  • 109
  • 136