user1777907
user1777907

Reputation: 1375

Makefile: Compiling from directory to another directory

I am trying to use Makefile to compile a bunch of .cpp files located in src/code/*.cpp, then compile each *.o in build/, and finally generate executable with those in build/ as well.

I have read a couple answers that I tried to work with but have encountered issues I do not understand.

CC = g++
FLAGS = -g -c

SOURCEDIR = /src/code
BUILDDIR = build

EXECUTABLE = DesktopSpecificController
SOURCES = $(wildcard src/code/*.cpp)
OBJECTS = $(patsubst src/code/*.cpp,build/%.o,$(SOURCES))

all: dir $(BUILDDIR)/$(EXECUTABLE)

dir:
    mkdir -p $(BUILDDIR)

$(BUILDDIR)/$(EXECUTABLE): $(OBJECTS)
    $(CC) $^ -o $@

$(OBJECTS): $(BUILDDIR)/%.o : $(SOURCEDIR)/%.cpp
    $(CC) $(FLAGS) $< -o $@

clean:
    rm -f $(BUILDDIR)/*o $(BUILDDIR)/$(EXECUTABLE)

I do get the following error, and I am not sure why:

Makefile:19: target `src/code/main.cpp' doesn't match the target pattern

I also see that when trying to build the EXECUTABLE, it is not using the .o files, so it seems my rule is wrong here.

Upvotes: 19

Views: 44036

Answers (1)

MadScientist
MadScientist

Reputation: 101041

Your patsubst function is wrong; you can't use shell wildcard characters like *. You want:

OBJECTS = $(patsubst $(SOURCEDIR)/%.cpp,$(BUILDDIR)/%.o,$(SOURCES))

Also you should be using SOURCEDIR and BUILDDIR everywhere, not just in some places (otherwise you'll get inconsistencies). And finally, your SOURCEDIR value is wrong: it should not start with / I expect:

SOURCEDIR = src/code

SOURCES = $(wildcard $(SOURCEDIR)/*.cpp)

Upvotes: 23

Related Questions