编译目录中的所有源文件,并将obj存储在不同的目录中

时间:2017-11-19 18:13:46

标签: c++ makefile

以下是我的make文件

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

我想要编译源目录中的所有源文件。

make文件正在编译为

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

但输出应如下

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

makfile正在编译相同的源文件以生成两个不同的目标文件。我在哪里做错了? 我应该用什么代替

$(OBJS):$(API_SOURCE)Makefile

1 个答案:

答案 0 :(得分:1)

您的API_SOURCE变量包含multiply.cpp add.cpp,因此您的规则适用于:

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

因此$<始终扩展为multiply.cpp。正确的方法是写一个pattern rule

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