makefile multiple source file compilation rule in one step

I have a directory structure as below:
Makefile
src/
file1.cpp file2.cpp
inc/
file1.h file2.h
Now I wanted to write a make rule to create a ‘objs’ directory and put all my objects(.o files) in ‘objs’ and then build a library out of it. I wanted to do this in one shot rather than writing one rule for each .cpp file.
This is what I tried:

SRC_DIR:= src/
INC_DIR:=inc/

SRC_PATH:=$(foreach var, $(SRC_DIR), $(wildcard $(var)*.cpp))
OBJ_PATH:=$(patsubst %.cpp,%.o,$(SRC_PATH))
OBJ_PATH:=$(notdir $(OBJ_PATH))
OBJ_DIR:=./objs
OBJ_PATH:=$(addprefix $(OBJ_DIR)/,$(OBJ_PATH))

TARGET:=libcommon.a

all:$(TARGET)

$(TARGET): $(OBJ_PATH)
    ar -rcs $(TARGET) $(OBJ_PATH)
$(OBJ_PATH): $(SRC_PATH)    
    mkdir -p $(OBJ_DIR)
    $(CXX) -o $(OBJ_PATH) -c $(SRC_PATH) -I$(INC_DIR)

But I am getting this error:

[root@localhost common]# make
mkdir -p ./objs
g++   -o ./objs/file1.o ./objs/file2.o -c  src/file1.cpp src/file2.cpp -Iinc/
g++: ./objs/file1.o: No such file or directory
g++: cannot specify -o with -c or -S with multiple files

I did a lot of search in this topic. Didn’t get any help. Please point me the mistake I am doing.


Source: gcc

Leave a Reply