soumya sambit Kunda
soumya sambit Kunda

Reputation: 508

Compile All source file in a directory and store objs in different directory

Following is my make file

CC = g++

CFLAGS = -Wall -c -fPIC

INCLUDES = -I${HOME}/ComingSoon/api/include

LFLAGs = -L${HOME}/ComingSoon/lib

LIB_DIR = ${HOME}/ComingSoon/lib

LIBS = -lapi
API_SRCDIR = ${HOME}/ComingSoon/api/source
API_SOURCE = $(wildcard ${HOME}/ComingSoon/api/source/*.cpp)
#API_SOURCE    = $(shell find $(API_SRCDIR) -name '*.cpp')
API_OBJ_SOURCE = $(wildcard ${HOME}/ComingSoon/api/obj/*.o)

OBJS_DIR_API = ${HOME}/ComingSoon/api/obj/

OBJS = $(patsubst $(API_SRCDIR)/%.cpp,$(OBJS_DIR_API)%.o,$(API_SOURCE))

api: $(OBJS)

$(OBJS): $(API_SOURCE) Makefile
    $(CC) $(CFLAGS) $(INCLUDES) $< -o  $@

clean_api:
    rm -rf ${HOME}/ComingSoon/lib/*.so
    rm -rf ${HOME}/ComingSoon/api/obj/*.o

I want to complie all the source files in the source directory.

The make file is compiling as

g++ -Wall -c -fPIC -I/home/soumya/ComingSoon/api/include /home/soumya/ComingSoon/api/source/multiply.cpp -o  /home/soumya/ComingSoon/api/obj/multiply.o
g++ -Wall -c -fPIC -I/home/soumya/ComingSoon/api/include /home/soumya/ComingSoon/api/source/multiply.cpp -o  /home/soumya/ComingSoon/api/obj/add.o

But the output should be as follows

g++ -Wall -c -fPIC -I/home/soumya/ComingSoon/api/include /home/soumya/ComingSoon/api/source/multiply.cpp -o  /home/soumya/ComingSoon/api/obj/multiply.o
g++ -Wall -c -fPIC -I/home/soumya/ComingSoon/api/include /home/soumya/ComingSoon/api/source/add.cpp -o  /home/soumya/ComingSoon/api/obj/add.o

The makfile is compiling the same source file to make two different object file. Where I am doing wrong? What should I use in place of

$(OBJS): $(API_SOURCE) Makefile

Upvotes: 0

Views: 46

Answers (1)

Beta
Beta

Reputation: 99104

Your API_SOURCE variable contains multiply.cpp add.cpp, so your rule comes out to:

$(OBJS): multiply.cpp add.cpp Makefile
    $(CC) ... $< -o  $@

So $< always expands to multiply.cpp. The correct way is to write a pattern rule:

$(OBJS_DIR_API)%.o: $(API_SRCDIR)/%.cpp Makefile
    $(CC) ... $< -o  $@

Upvotes: 1

Related Questions