Hailiang Zhang
Hailiang Zhang

Reputation: 18950

Makefile to generate objects to a different directory

I have source codes in the "src/" folder, and want to write a Makefile to generate objects files in the "lib/" folder. Following is the code I tried, but it did not work:

DIRSRC=src/
DIRLIB=lib/

SRC=a.cc b.cc c.cc
OBJ=$(SRC:.cc=.o)

$(OBJ): $(DIRLIB)%.o: $(DIRSRC)%.cc
    $(CC) -c $< -o $@

Apparently the error comes from the last pattern rule. I know there is a simply solution, but not sure what is that.

Upvotes: 1

Views: 67

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 81022

You want to use something like:

DIRSRC=src/
DIRLIB=lib/

SRC=a.cc b.cc c.cc
# Add DIRLIB to the beginning of each entry in OBJ so that they match the static pattern rule target-pattern.
OBJ=$(addprefix $(DIRLIB),$(SRC:.cc=.o))

# Give make a default target that builds all your object files.
all: $(OBJ)

$(OBJ): $(DIRLIB)%.o: $(DIRSRC)%.cc
        $(CC) -c $< -o $@

Upvotes: 1

Related Questions